Frequency Queries

  • + 0 comments

    Here is a shorter variant in Python3 that uses a frequency dictionary of sets rather than of ints. I was inspired by fromtheeast1's use of a frequency dictionary f, which prevents a timeout on the longer query lists. This success is due to a dict's or set's find-by-value time being O(1) average and O(n) worst, whereas a list's find-by-value time is O(n) average.

    from collections import defaultdict
    def freqQuery(queries):
    
        d, f = defaultdict(int), defaultdict(set)
        for c,v in queries:
            if c==3 : yield 1 if f[v] else 0 ; continue
            f[d[v]].discard(v)
            if c==1 : d[v] += 1
            elif d[v] : d[v] -= 1
            f[d[v]].add(v)