Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
k most frequent in linear time
Next article icon

Find top k (or most frequent) numbers in a stream

Last Updated : 03 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an array of n numbers. Your task is to read numbers from the array and keep at-most K numbers at the top (According to their decreasing frequency) every time a new number is read. 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.

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
Recommended Problem
Top k numbers in a stream
Solve Problem

Approach: The idea is to store the top k elements with maximum frequency. To store them a vector or an array can be used. To keep the track of frequencies of elements creates a HashMap to store element-frequency pairs. Given a stream of numbers, when a new element appears in the stream update the frequency of that element in HashMap and put that element at the end of the list of K numbers (total k+1 elements) now compare adjacent elements of the list and swap if higher frequency element is stored next to it.

Algorithm: 

  1. Create a Hashmap hm, and an array of k + 1 length.
  2. Traverse the input array from start to end.
  3. Insert the element at k+1 th position of the array, and update the frequency of that element in HashMap.
  4. Now, iterate from the position of element to zero.
  5. For very element, compare the frequency and swap if a higher frequency element is stored next to it, if the frequency is the same then the swap is the next element is greater.
  6. print the top k element in each traversal of the original array.

Implementation: 

C++




// C++ program to find top k elements in a stream
#include <bits/stdc++.h>
using namespace std;
 
// Function to print top k numbers
void kTop(int a[], int n, int k)
{
    // vector of size k+1 to store elements
    vector<int> top(k + 1);
 
    // array to keep track of frequency
    unordered_map<int, int> freq;
 
    // iterate till the end of stream
    for (int m = 0; m < n; m++) {
        // increase the frequency
        freq[a[m]]++;
 
        // store that element in top vector
        top[k] = a[m];
 
        // search in top vector for same element
        auto it = find(top.begin(), top.end() - 1, a[m]);
 
        // iterate from the position of element to zero
        for (int i = distance(top.begin(), it) - 1; i >= 0; --i) {
            // compare the frequency and swap if higher
            // frequency element is stored next to it
            if (freq[top[i]] < freq[top[i + 1]])
                swap(top[i], top[i + 1]);
 
            // if frequency is same compare the elements
            // and swap if next element is high
            else if ((freq[top[i]] == freq[top[i + 1]])
                     && (top[i] > top[i + 1]))
                swap(top[i], top[i + 1]);
            else
                break;
        }
 
        // print top k elements
        for (int i = 0; i < k && top[i] != 0; ++i)
            cout << top[i] << ' ';
    }
    cout << endl;
}
 
// Driver program to test above function
int main()
{
    int k = 4;
    int arr[] = { 5, 2, 1, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    kTop(arr, n, k);
    return 0;
}
 
 

Java




import java.io.*;
import java.util.*;
class GFG {
 
    // function to search in top vector for element
    static int find(int[] arr, int ele)
    {
        for (int i = 0; i < arr.length; i++)
            if (arr[i] == ele)
                return i;
        return -1;
    }
 
    // Function to print top k numbers
    static void kTop(int[] a, int n, int k)
    {
        // vector of size k+1 to store elements
        int[] top = new int[k + 1];
 
        // array to keep track of frequency
        HashMap<Integer, Integer> freq = new HashMap<>();
        for (int i = 0; i < k + 1; i++)
            freq.put(i, 0);
 
        // iterate till the end of stream
        for (int m = 0; m < n; m++) {
            // increase the frequency
            if (freq.containsKey(a[m]))
                freq.put(a[m], freq.get(a[m]) + 1);
            else
                freq.put(a[m], 1);
 
            // store that element in top vector
            top[k] = a[m];
 
            // search in top vector for same element
            int i = find(top, a[m]);
            i -= 1;
 
            // iterate from the position of element to zero
            while (i >= 0) {
                // compare the frequency and swap if higher
                // frequency element is stored next to it
                if (freq.get(top[i]) < freq.get(top[i + 1])) {
                    int temp = top[i];
                    top[i] = top[i + 1];
                    top[i + 1] = temp;
                }
 
                // if frequency is same compare the elements
                // and swap if next element is high
                else if ((freq.get(top[i]) == freq.get(top[i + 1])) && (top[i] > top[i + 1])) {
                    int temp = top[i];
                    top[i] = top[i + 1];
                    top[i + 1] = temp;
                }
 
                else
                    break;
                i -= 1;
            }
 
            // print top k elements
            for (int j = 0; j < k && top[j] != 0; ++j)
                System.out.print(top[j] + " ");
        }
        System.out.println();
    }
 
    // Driver program to test above function
    public static void main(String args[])
    {
        int k = 4;
        int[] arr = { 5, 2, 1, 3, 2 };
        int n = arr.length;
        kTop(arr, n, k);
    }
}
 
// This code is contributed by rachana soma
 
 

Python3




# Python program to find top k elements in a stream
 
# Function to print top k numbers
def kTop(a, n, k):
 
    # list of size k + 1 to store elements
    top = [0 for i in range(k + 1)]
  
    # dictionary to keep track of frequency
    freq = {i:0 for i in range(k + 1)}
 
    # iterate till the end of stream
    for m in range(n):
 
        # increase the frequency
        if a[m] in freq.keys():
            freq[a[m]] += 1
        else:
            freq[a[m]] = 1
 
        # store that element in top vector
        top[k] = a[m]
  
        i = top.index(a[m])
        i -= 1
         
        while i >= 0:
 
            # compare the frequency and swap if higher
            # frequency element is stored next to it
            if (freq[top[i]] < freq[top[i + 1]]):
                t = top[i]
                top[i] = top[i + 1]
                top[i + 1] = t
             
            # if frequency is same compare the elements
            # and swap if next element is high
            else if ((freq[top[i]] == freq[top[i + 1]]) and (top[i] > top[i + 1])):
                t = top[i]
                top[i] = top[i + 1]
                top[i + 1] = t
            else:
                break
            i -= 1
         
        # print top k elements
        i = 0
        while i < k and top[i] != 0:
            print(top[i],end=" ")
            i += 1
    print()
  
# Driver program to test above function
k = 4
arr = [ 5, 2, 1, 3, 2 ]
n = len(arr)
kTop(arr, n, k)
 
# This code is contributed by Sachin Bisht
 
 

C#




// C# program to find top k elements in a stream
using System;
using System.Collections.Generic;
 
class GFG {
    // function to search in top vector for element
    static int find(int[] arr, int ele)
    {
        for (int i = 0; i < arr.Length; i++)
            if (arr[i] == ele)
                return i;
        return -1;
    }
 
    // Function to print top k numbers
    static void kTop(int[] a, int n, int k)
    {
        // vector of size k+1 to store elements
        int[] top = new int[k + 1];
 
        // array to keep track of frequency
        Dictionary<int,
                   int>
            freq = new Dictionary<int,
                                  int>();
        for (int i = 0; i < k + 1; i++)
            freq.Add(i, 0);
 
        // iterate till the end of stream
        for (int m = 0; m < n; m++) {
            // increase the frequency
            if (freq.ContainsKey(a[m]))
                freq[a[m]]++;
            else
                freq.Add(a[m], 1);
 
            // store that element in top vector
            top[k] = a[m];
 
            // search in top vector for same element
            int i = find(top, a[m]);
            i--;
 
            // iterate from the position of element to zero
            while (i >= 0) {
                // compare the frequency and swap if higher
                // frequency element is stored next to it
                if (freq[top[i]] < freq[top[i + 1]]) {
                    int temp = top[i];
                    top[i] = top[i + 1];
                    top[i + 1] = temp;
                }
 
                // if frequency is same compare the elements
                // and swap if next element is high
                else if (freq[top[i]] == freq[top[i + 1]] && top[i] > top[i + 1]) {
                    int temp = top[i];
                    top[i] = top[i + 1];
                    top[i + 1] = temp;
                }
                else
                    break;
 
                i--;
            }
 
            // print top k elements
            for (int j = 0; j < k && top[j] != 0; ++j)
                Console.Write(top[j] + " ");
        }
        Console.WriteLine();
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int k = 4;
        int[] arr = { 5, 2, 1, 3, 2 };
        int n = arr.Length;
        kTop(arr, n, k);
    }
}
 
// This code is contributed by
// sanjeev2552
 
 

Javascript




<script>
 
      // JavaScript program to find top k elements in a stream
      // function to search in top vector for element
      function find(arr, ele) {
        for (var i = 0; i < arr.length; i++)
        if (arr[i] === ele) return i;
        return -1;
      }
 
      // Function to print top k numbers
      function kTop(a, n, k) {
        // vector of size k+1 to store elements
        var top = new Array(k + 1).fill(0);
 
        // array to keep track of frequency
 
        var freq = {};
        for (var i = 0; i < k + 1; i++) freq[i] = 0;
 
        // iterate till the end of stream
        for (var m = 0; m < n; m++) {
          // increase the frequency
          if (freq.hasOwnProperty(a[m])) freq[a[m]]++;
          else freq[a[m]] = 1;
 
          // store that element in top vector
          top[k] = a[m];
 
          // search in top vector for same element
          var i = find(top, a[m]);
          i--;
 
          // iterate from the position of element to zero
          while (i >= 0) {
            // compare the frequency and swap if higher
            // frequency element is stored next to it
            if (freq[top[i]] < freq[top[i + 1]]) {
              var temp = top[i];
              top[i] = top[i + 1];
              top[i + 1] = temp;
            }
 
            // if frequency is same compare the elements
            // and swap if next element is high
            else if (freq[top[i]] === freq[top[i + 1]] &&
            top[i] > top[i + 1])
            {
              var temp = top[i];
              top[i] = top[i + 1];
              top[i + 1] = temp;
            } else break;
 
            i--;
          }
 
          // print top k elements
          for (var j = 0; j < k && top[j] !== 0; ++j)
            document.write(top[j] + " ");
        }
        document.write("<br>");
      }
 
      // Driver Code
      var k = 4;
      var arr = [5, 2, 1, 3, 2];
      var n = arr.length;
      kTop(arr, n, k);
       
</script>
 
 
Output: 
5 2 5 1 2 5 1 2 3 5 2 1 3 5

 

Complexity Analysis: 

  • 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). 
    To store the elements in HashMap O(n) space is required.

 



Next Article
k most frequent in linear time
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Accolite
  • Amazon
  • array-stream
  • cpp-unordered_map
  • Order-Statistics
Practice Tags :
  • Accolite
  • Amazon
  • Arrays
  • Hash

Similar Reads

  • Average of max K numbers in a stream
    Given a list of N numbers, and an integer 'K'. The task is to print the average of max 'K' numbers after each query where a query consists of an integer element that needs to be added to the list of elements. Note: The queries are defined with an integer array 'q' Examples: Input: N = 4, K = 3, arr
    8 min read
  • Find the k most frequent words from data set in Python
    The goal is to find the k most common words in a given dataset of text. We'll look at different ways to identify and return the top k words based on their frequency, using Python. Using collections.Countercollections.Counter that works like a dictionary, but its main job is to count how many times e
    3 min read
  • k most frequent in linear time
    Given an array of integers, we need to print k most frequent elements. If there is a tie, we need to prefer the elements whose first appearance is first. Examples: Input : arr[] = {10, 5, 20, 5, 10, 10, 30}, k = 2 Output : 10 5 Input : arr[] = {7, 7, 6, 6, 6, 7, 5, 4, 4, 10, 5}, k = 3 Output : 7 6 5
    12 min read
  • Find given occurrences of Mth most frequent element of Array
    Given an array arr[], integer M and an array query[] containing Q queries, the task is to find the query[i]th occurrence of Mth most frequent element of the array. Examples: Input: arr[] = {1, 2, 20, 8, 8, 1, 2, 5, 8, 0, 6, 8, 2}, M = 1, query[] = {100, 4, 2}Output: -1, 12, 5Explanation: Here most f
    9 min read
  • Find Mode in a list of numbers
    Given a linked list and the task is to find the mode of the linked list. Note: Mode is the value that appears most frequently in the Linked list. Examples: Input: List: 1 -> 2 -> 3 -> 2 -> 4 -> 3 -> 2 -> 5 -> 2Output: 2Explanation: 2 is the value that appears most frequently
    6 min read
  • Find minimum subarray length to reduce frequency
    Given an array arr[] of length N and a positive integer k, the task is to find the minimum length of the subarray that needs to be removed from the given array such that the frequency of the remaining elements in the array is less than or equal to k. Examples: Input: n = 4, arr[] = {3, 1, 3, 6}, k =
    10 min read
  • K'th largest element in a stream
    Given an infinite stream of integers, find the Kth largest element at any point of time. Note: Here we have a stream instead of a whole array and we are allowed to store only K elements. Examples: Input: stream[] = {10, 20, 11, 70, 50, 40, 100, 5, . . .}, K = 3Output: {_, _, 10, 11, 20, 40, 50, 50,
    14 min read
  • Find elements having at least K times the minimum frequency
    Given an array A, the task is to find elements with the occurrence at least K times the frequency of the least occurring element in the array. Examples: Input: A = {4, 4, 3, 6, 6, 6, 8, 9}, K = 2Output: {4, 6}Explanation: Frequency Table : {4:2, 3:1, 6:3, 8:1, 9:1}, least occurring elements in nums
    6 min read
  • Numbers with prime frequencies greater than or equal to k
    Given an array, find elements that appear a prime number of times in the array with a minimum k frequency (frequency >= k). Examples : Input : int[] arr = { 11, 11, 11, 23, 11, 37, 51, 37, 37, 51, 51, 51, 51 }; k = 2 Output : 37, 51 Explanation : 11's count is 4, 23 count 1, 37 count 3, 51 count
    6 min read
  • Most frequent factor in a range of integers
    You are given a range of numbers, from lower number to higher number (both inclusive). Consider all the factors of these numbers except 1, the task is to find the factor which appears the maximum number of times. If more than one number have maximum frequency then print anyone of them.Examples: Inpu
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences