Frequency Queries

  • + 8 comments

    This solution in Python, and it passed all test cases.

    def freqQuery(queries):
        d = defaultdict(lambda: 0)
        f = defaultdict(lambda: 0)
        output = []
        for command, key in queries: # O(n) queries
            if command == 1:
                f[d[key]] = max(0, f[d[key]] - 1)
                d[key] += 1
                f[d[key]] += 1
            elif command == 2:
                f[d[key]] = max(0, f[d[key]] - 1)
                d[key]= max(0, d[key] - 1)
                if d[key] > 0:
                    f[d[key]] += 1
            else:
                if f[key] > 0: # O(1)
                    output.append(1)
                else:
                    output.append(0)
        return output