I cant understand this, please can u expain?

I cant understand this, please can u expain?

Hey @haseebshaik00

We basically need to print top k numbers sorted by frequency when input stream has included k distinct elements, else need to print all distinct elements sorted by frequency.
i can explain you better with examples :-
Input : arr[] = {5, 2, 1, 3, 2}
k = 4
Output : 5 2 5 1 2 5 1 2 3 5 2 1 3 5
Explanation:

  1. After reading 5, there is only one element 5 whose frequency is max till now.
    so print 5.
  2. After reading 2, we will have two elements 2 and 5 with the same frequency.
    As 2, is smaller than 5 but their frequency is the same so we will print 2 5.
  3. After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency,
    so print 1 2 5.
  4. Similarly after reading 3, print 1 2 3 5
  5. After reading last element 2 since 2 has already occurred so we have now a
    frequency of 2 as 2. So we keep 2 at the top and then rest of the element
    with the same frequency in sorted order. So print, 2 1 3 5.

Input : arr[] = {5, 2, 1, 3, 4}
k = 4
Output : 5 2 5 1 2 5 1 2 3 5 1 2 3 4
Explanation:

  1. After reading 5, there is only one element 5 whose frequency is max till now.
    so print 5.
  2. After reading 2, we will have two elements 2 and 5 with the same frequency.
    As 2, is smaller than 5 but their frequency is the same so we will print 2 5.
  3. After reading 1, we will have 3 elements 1, 2 and 5 with the same frequency,
    so print 1 2 5.
    Similarly after reading 3, print 1 2 3 5
  4. After reading last element 4, All the elements have same frequency
    So print, 1 2 3 4.

can you please tell how to approach

Hey @haseebshaik00
You can do this question without using heap .
Refer this https://www.geeksforgeeks.org/find-top-k-or-most-frequent-numbers-in-a-stream/

For heap based approach, read this discussion Top k most frequent in a stream of integers

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.