SIR/MAM,
please tell me the approach to solve this problem using heap;
Top k most frequent number in a stream problem
There are 2 ways by which you can solve this problem using heaps.
- Using a MAX-HEAP (with no size limit): Build a max heap based on frequency count of integers. At the end, the top k elements of your max heap will be the k most frequent in the stream.
- Using a MIN-Heap of size K (more efficient):Maintain a min heap of size k based on frequency count of integers.
algo:
make a heap for each i no of elements . for each heap element have a freq , and digit as its field

now
for(int i =0 ; i < n ; i++):
u need for each j from 0 to i :
make a heap sorted acc to freq and secondly on the basis of increasing order of number
now pop first k elements of the heap and print them
+ in case the size of heap is less than k print elements of heap
end:
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.