Frequency Queries

  • + 0 comments

    So I rewrote your solution with some comments to try and figure out your logic. Can you check to see if I've understood it?

    def freqQuery(queries):
        arr = dict() # val:count of said values    
        freq = dict() #number of counts, ie 1:numbers that appear only
        out = []
    
    for (oper, val) in queries:
        if (oper == 1):
            #insertion
            if not(val in arr):
                arr[val] = 0 #if value isn't in arr dict, then add value to dict and give it a 0 bc we can't assign a 1 just yet
            if not(arr[val] in freq):
                freq[arr[val]] = 1 #if freq dictionary doesn't already have arr[val]'s number, then we automatically assign by 1
            freq[arr[val]] -= 1 #subtracting arr[val]'s number by one because it's always kept at 1
            arr[val] += 1 #adding 1 to arr[val]
            if not(arr[val] in freq):
                freq[arr[val]] = 0  #if arr[val]'s cnt isn't in freq, then we assign it 0
            freq[arr[val]] += 1 #otherwise we increase it by 1
    
        if (oper == 2) and (val in arr):
            #deletion
            freq[arr[val]] -= 1 #same as above, we subtract 1 from it to keep it at 1
            arr[val] -= 1
            freq[arr[val]] += 1 #same as above, we add 1 from it to keept it at one
    
            if arr[val] <= 0:
                arr.pop(val)
    
        if (oper == 3) and (val in freq):
            out.append(int(freq[val]>0))
        elif(oper == 3):
            out.append(0)
    return out