Top K Frequent Elements
Min-Heap
Problem
Given a non-empty array of integers, return the k most frequent elements.
For example:
Thought Process
This problem is very similar to how we solved K Closest Points but in this problem we are storing (frequency, number) pairs in our heap.
We want the top K elements, this is why a min-heap is good.
Solution
Key Points
Using min-heap to store elements according to their frequency count so we get the top K
Storing the frequency count and number together in pairs in the heap
Time Complexity
Time:
Space: because even though we are storing only ‘K’ numbers in the heap. For the frequency map, however, we need to store all the ‘N’ numbers.
Last updated
Was this helpful?