Frequency Queries

  • + 1 comment

    mine was failing those cases when I used an array and object for frequencies and counts, but when I switched to 2 objects, it started passing ...that said, I am still failing 3 other edge case right now and I'm not sure why. Thanks for your post, it may help

    it just dawned on me that you are checking for the value during a delete not just to prevent illegally going negative, but because it actually says "if present"! .. My solution here uses something similar to python's counter (naaomi_ngyuen7's solution above uses that, and since I came here for the final 3 cases I figured I could improve readability of mine with something similar):

    function freqQuery(queries) {
        const counterFactory = () => new Proxy({}, { get(o, p) { return o.hasOwnProperty(p) ? o[p] : 0 } })
        const counts = counterFactory()
        const frequencies = counterFactory()
        const transcript = []
    
        queries.forEach(([action, value]) => {
            switch (action) {
                case 1: // add
                  frequencies[counts[value]] -= 1
                  counts[value] += 1
                  frequencies[counts[value]]+= 1
                  break
                case 2: // delete
                  if (counts[value]) { 
                    frequencies[counts[value]] -= 1
                    counts[value] -= 1
                    frequencies[counts[value]] += 1
                  }
                  break
                case 3: // check
                  transcript.push(frequencies[value] ? 1 : 0)
                  break
                default:
                  console.warn('unknown action', action, 'with value', value, 'at index', i)
            }
        })
    
        return transcript
    }