Given an array A with possible duplicate entries, find the k entries that occur most frequently.
My approach:
Create a MinHeap of k most occurring elements ordered by the frequency. top element obviously being least occurring of rest of the elements. Create a HashMap to keep track of all element counts and whether or not they are in MinHeap.
When reading a new integer:
- check if it is in HashMap: Increment the count in HashMap
- also if it is check if it is in Heap :then Increment the count there also and heapify.
- if not then compare with root element count and remove the root to add this if necessary. Then heapify.
In the end return MinHeap as desired output.
class Wrapper{
boolean inHeap;
int count;
}
This would take O(n+k) space and O(n log k) time complexity. Is there a better way to do space and/or time complexity wise.