VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-top-k-or-most-frequent-numbers-in-a-stream/

⇱ Top k Frequent in a Stream - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Top k Frequent in a Stream

Last Updated : 1 May, 2026

Given an array of n numbers, process the elements one by one and maintain at most k elements with the highest frequency. After each insertion, include the elements sorted by decreasing frequency, and if frequencies are equal then smaller values come first. If the number of distinct elements is less than k, include all of them, otherwise include only the top k elements.

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, only one element exists, so print 5.
2. After reading 2, both have the same frequency, so the smaller element comes first: 2 5.
3. After reading 1, all have the same frequency, so print in sorted order: 1 2 5.
4. After reading 3, all still have the same frequency, so print: 1 2 3 5.
5. After reading last 2, its frequency becomes highest, so it comes first, and the rest are printed in sorted order: 2 1 3 5.

Input: arr[] = {5, 2, 1, 4} k = 3
Output:
5
2 5
1 2 5
1 2 4
Explanation:
1. After reading 5, only one element exists, so print 5.
2. After reading 2, both have the same frequency, so the smaller element comes first: 2 5.
3. After reading 1, all have the same frequency, so print in sorted order: 1 2 5.
4. After reading 4, all elements have the same frequency, so print top k = 3 elements: 1 2 4.

Using Hash Map and Array

  • Maintain a Hash Map to store the frequency of each element.
  • Use an array of size k+1 to store current top elements.
  • For each incoming element, update its frequency and insert it at the correct position in the array. This step takes O(k) time.

Output
5 
2 5 
1 2 5 
1 2 3 5 
2 1 3 5 

Time Complexity: O( n * k ), In each traversal the temp array of size k is traversed, So the time Complexity is O( n * k ).
Space Complexity: O(n)

Comment