sir/mam,
please tell how to approach this problem
Top k most frequent number in a stream
Algorithm :
- Create a Hashmap hm , and an array of k + 1 length.
- Traverse the input array from start to end.
- Insert the element at k+1 th position of the array, update the frequency of that element in HashMap.
- Now, traverse the temp array from start to end – 1
- For very element, compare the frequency and swap if higher frequency element is stored next to it, if the frequency is same then swap is the next element is greater.
- print the top k element in each traversal of original array.
Please give a heap based solution .
Algorithm : using heap
- Create a Hashmap hm , to store key-value pair, i.e. element-frequency pair.
- Traverse the array from start to end.
- For every element in the array update hm[array[i]]++
- Store the element-frequency pair in a Priority Queue and create the Priority Queue, this takes O(n) time.
- Run a loop k times, and in each iteration remove the top of the priority queue and print the element.
Please share me the code .i cant code this .
we can’t directly share the code as it is not beneficial for you
first try to do something
send the code link
i will help you then
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.