19. Top k numbers in a stream
Last updated
Last updated
The problem can be found at the following link: Question Link
To solve this problem, I uses an unordered_map freqMap
to keep track of the frequency of each number in the stream and uses a set, topKSet
, to maintain the top k numbers along with their frequencies. The set is sorted based on frequencies in descending order and, for ties, by the number itself in ascending order.
Then, for each element in the stream, the code checks if the number is already present in the freqMap
.
If it is, it removes the existing entry for that number from topKSet
to update the frequency.
Then, it increments the frequency in the freqMap
and inserts the updated frequency and number into topKSet
.
The set is then iterated to get the top k numbers, and these are stored in a temporary vector.
Time Complexity: O(N*K)
.
Auxiliary Space Complexity: The space complexity is O(N)
to store the frequency map and the result vector.
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.