Problem :

https://www.hackerrank.com/challenges/frequency-queries/problem


My Solution :

#!/usr/bin/env python3

def solve(queries):
    count_dic = {}
    freq_dic = {}
    for case, data in queries:
        if case == 1:
            count = count_dic.setdefault(data, 0)
            freq = freq_dic.setdefault(count, 1)
            count_dic[data] += 1
            freq_dic.setdefault(count+1, 0)
            freq_dic[count+1] += 1
            freq_dic[count] -= 1
        elif case == 2:
            count = count_dic.setdefault(data, 0)
            freq = freq_dic.setdefault(count, 1)
            if count > 0:
                count_dic[data] -= 1
                freq_dic.setdefault(count-1, 0)
                freq_dic[count-1] += 1
                freq_dic[count] -= 1
        else:
            yield 1 if freq_dic.get(data, 0) > 0 else 0


q = int(input())
queries = []
for _ in range(q):
    queries.append(list(map(int, input().rstrip().split())))
for result in solve(queries):
    print(result)


My Solution2 :

동일한 풀이를 dictionary 대신 list로 처리해보려 하였으나 python 32비트에서 list 최대 size가 536,870,912 라서 10**9만큼 0으로 초기화 할 수 없었다. 대신 collections의 defaultdict로 코드 라인 수를 조금 줄여보았다.

#!/usr/bin/env python3

from collections import defaultdict

def solve(queries):
    cnt = defaultdict(int)
    freq = defaultdict(int)
    for case, data in queries:
        if case == 1:
            cnt[data] += 1
            freq[cnt[data]] += 1
            freq[cnt[data]-1] -= 1
        elif case == 2:
            if cnt[data] > 0:
                cnt[data] -= 1
                freq[cnt[data]] += 1
                freq[cnt[data]+1] -= 1
        else:
            yield 1 if freq[data] > 0 else 0


q = int(input())
queries = []
for _ in range(q):
    queries.append(list(map(int, input().rstrip().split())))
for result in solve(queries):
    print(result)