Top k most frequent number in a stream

can u pls explain the sample input and output because im not gettng this question?

Hello @sktg99,

Let’s understand this problem with the help of two examples:

  1. arr[] = {5, 2, 1, 3, 2}
    k = 4
    Output :
    5 2 5 1 2 5 1 2 3 5 2 1 3 5
    Explanation:
    Given array is arr[] = {5, 2, 1, 3, 2} and k = 4
    Step 1:After reading 5, there is only one element 5 whose frequency is max till now. so print 5.
    Step 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.
    Step 3: After reading 1, we will have 3 elements 1,2 and 5 with the same frequency, so print 1 2 5.
    Step 4: Similarly after reading 3, print 1 2 3 5
    Step 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.

  2. arr[] = {5, 2, 1, 3, 4}
    k = 4
    Output :
    5 2 5 1 2 5 1 2 3 5 1 2 3 4
    Explanation:
    Given array is arr[] = {5, 2, 1, 3, 4} and k = 4
    Step 1:After reading 5, there is only one element 5 whose frequency is max till now. so print 5.
    Step 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.
    Step 3: After reading 1, we will have 3 elements 1,2 and 5 with the same frequency, so print 1 2 5.
    Step 4: Similarly after reading 3, print 1 2 3 5
    Step 5: After reading the last element 4, since 4 is smaller than 5. So we keep 4 at the top and then rest of the element with the same frequency in sorted order and will discard 5 as k=4. So print, 2 1 3 4.

Approach:

  • Iterate through the array which contains a stream of numbers.
  • To keep track of top k elements, make a top vector of size k+1.
  • For every element in the stream increase its frequency and store it in the last position of the top vector. We can use hashing for efficiently fetching frequency of an element and increasing it.
  • Now find the position of the element in top vector and iterate from that position to zero. For finding a position we can make use of the find() function in C++ STL, it returns an iterator pointing to the element if found in the vector.
  • And make that list of k+1 numbers sorted according to the frequency and their value.
  • Print top k elements form a top vector.
  • Repeat the above steps for every element in the stream.

Hope, this would help.
Give a like if you are satisfied.

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.