A moderation tool watches which user ids post in a chat room. Posts arrive and get deleted, and at any moment a moderator may ask: "is there someone who has posted exactly f times right now?" The room is busy, so every operation has to be fast.
Implement a class FrequencyTracker with:
add(value): records one more occurrence of value.
remove(value): removes one occurrence of value and returns true, or returns false and changes nothing if value is not present.
hasFrequency(f): returns true if some value currently occurs exactly f times, otherwise false.
Also write answerFrequencyQueries(queries), which runs a list of [op, x] pairs on a new tracker: op1 adds x, 2 removes x, and 3 asks hasFrequency(x). It returns the answers to the 3 queries, in order.
Rules:
Values are safe integers (they can be negative or zero). f must be a positive safe integer.
Throw a TypeError for a value or f that breaks rule 1, for a query that is not a two-element array, and for an op other than 1, 2 or 3.
There can be 200,000 operations and 100,000 distinct values at once. Every method must run in O(1) average time; scanning the counts for each question is too slow.
answerFrequencyQueries([[1, 5], [1, 6], [3, 2], [1, 10], [1, 10], [1, 6], [2, 5], [3, 2]]);// [false, true]: after the last query, 6 and 10 both occur twiceconst tracker = new FrequencyTracker();tracker.add(7);tracker.add(7);tracker.hasFrequency(2); // truetracker.remove(7); // truetracker.hasFrequency(2); // falsetracker.remove(3); // false: 3 was never added
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
2
code listings
5
edge cases
What's inside
The full problem, with examples
Tests that check your solution
Step-by-step
Approach
Solution
Complexity
Edge cases
Follow-up questions
Card worldwide
UPI and net banking in India
One-time payment, nothing renews
Private, and saved in this browser as you type. All your notes are on My lists.