See the original problem on HackerRank.
Warning: the problem I/O might result slow. For some languages (e.g. C++), it's better off reading the whole input first.
This problem requires some additional storage to be solved efficiently. Using only one hash map is not enough because of operation of type 3.
The idea is to use a hash map to store the frequencies of each element (query type 1 and 2) and also an additional hash map “histogram”, that is an inverse map from frequency to elements having such a frequency.
Here is a Python implementation:
We can even improve our algorithm by noticing that the maximum frequency is fixed to \( 10^6 \) (we have at most that number of queries, read the problem constraints) so we can replace the histogram with a static array.
Here is the idea in C++:
Sometimes the histogram should contain the identity of each element appearing a certain number of time. In this case, an approach similar to that presented in Python is better.
We should consider some tradeoffs such as:
- how much storage can I use (balance between efficienty and memory)
- need to show which elements have a certain frequency (the histogram should contain more information, like in Python approach)
- if the query of type 3 are a few, the histogram can be avoided - we hopefully can afford a map traversal
- we can compute the queries of type 3 in batch (between 1 and 2) if the answers are not needed in streaming (one in, one out)