Frequency Queries

  • + 0 comments

    approximately O(q) using unordered_map, which are hash objects

    each query takes constant time if there's no hash collison

    vector<int> freqQuery(const vector<vector<int>>& queries) {
        unordered_map<int, int> freq, freqCount;
        vector<int> answer;
        for (int i = 0; i < queries.size(); ++i) {
            if (queries[i][0] == 1) {
                auto it = freq.find(queries[i][1]);
                if (it != freq.end()) --freqCount[it->second];
                int t = ++freq[queries[i][1]];
                ++freqCount[t];
            }
            else if (queries[i][0] == 2) {
                auto it = freq.find(queries[i][1]);
                if (it != freq.end() and it->second != 0) {
                    --freqCount[it->second];
                    --it->second;
                    ++freqCount[it->second];
                }
            }
            else if (queries[i][0] == 3) {
                auto it = freqCount.find(queries[i][1]);
                if (it != freqCount.end() and it->second != 0) answer.push_back(1);
                else answer.push_back(0);
            }
        }
        return answer;
    }