Frequency Queries

  • + 1 comment

    Not shorter but this is a passable solution without the use of Counter from Collections:

    def freqQuery(queries):
    
        a1 = dict()  #Keep track of the number of times each queried number occurs in the array
        a2 = dict() #[0]*len(queries)  #Keep track of how many numbers occur once, twice, etc.
        
        out = []
    
        for (op,num) in queries:
    
            if  (op == 1):
                if not(num in a1):
                    a1[num] = 0
    
                if not(a1[num] in a2):
                    a2[a1[num]] = 1
    
                a2[a1[num]] -= 1
                
                a1[num] += 1
    
                if not(a1[num] in a2):
                    a2[a1[num]] = 0
    
                a2[a1[num]] += 1
            
            if (op == 2) & (num in a1):
    
                a2[a1[num]] -= 1
                a1[num] -= 1
                a2[a1[num]] += 1
    
                if a1[num] <= 0:
                    a1.pop(num)
                
    
            if (op == 3) & (num in a2):
                out.append(int(a2[num]>0))
                #out.append(a2[num])
    
            elif (op==3):
                out.append(0)
    
        return out