• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
January 20, 2024 |1.9K Views

PROBLEM OF THE DAY : 19/01/2024 | Top k numbers in a stream

Description
Discussion

Welcome to the daily solving of our PROBLEM OF THE DAY with Yash Dwivedi We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Array but also build up problem-solving skills.

In this problem, given N numbers in an array, your task is to keep at most the top K numbers with respect to their frequency.

In other words, you have to iterate over the array, and after each index, determine the top K most frequent numbers until that iteration and store them in an array in decreasing order of frequency. An array will be formed for each iteration and stored in an array of arrays. If the total number of distinct elements is less than K, then keep all the distinct numbers in the array. If two numbers have equal frequency, place the smaller number first in the array.

Example :

Input:
N=5, K=4
arr[] = {5, 2, 1, 3, 2} 
Output: 

2 5 
1 2 5 
1 2 3 5 
2 1 3 5 
Explanation:

Firstly there was 5 whose frequencyis max till now. So resulting sequence is {5}. Then came 2, which is smaller than 5 but their frequencies are same so resulting sequence is {2, 5}. Then came 1, which is the smallest among all thenumbers arrived, so resulting sequence is {1, 2, 5}. Then came 3 , so resulting sequence is {1, 2, 3, 5} Then again 2, which has the highestfrequency among all numbers,  so resulting sequence {2, 1, 3, 5}.

Give the problem a try before going through the video. All the best!!!
Problem Link: https://www.geeksforgeeks.org/problems/top-k-numbers3425/1