VOOZH about

URL: https://www.geeksforgeeks.org/dsa/mode-in-a-stream-of-integers-running-integers/

⇱ Mode in a stream of integers (running integers) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mode in a stream of integers (running integers)

Last Updated : 15 Jul, 2025

Given that integers are being read from a data stream. Find the mode of all the elements read so far starting from the first integer till the last integer.

Mode is defined as the element which occurs the maximum time. If two or more elements have the same maximum frequency, then take the one with the last occurrence. 

Examples:

Input: stream[] = {2, 7, 3, 2, 5}
Output: 2 7 3 2 2 
Explanation: 
Mode of Running Stream is computed as follows: 
Mode({2}) = 2 
Mode({2, 7}) = 7 
Mode({2, 7, 3}) = 3 
Mode({2, 7, 3, 2}) = 2 
Mode({2, 7, 3, 2, 2}) = 2

Input: stream[] = {3, 5, 9, 9, 2, 3, 3, 4}
Output: 3 5 9 9 9 3 3 3

Approach: The idea is to use a Hash-map to map elements to its frequency. While reading the elements one by one update the frequencies of elements in the map and also update the mode which will be the mode of the stream of the running integers.

Below is the implementation of the above approach:


Output: 
2 7 3 2 2

 

Performance Analysis: 

  • Time Complexity: O(N)
  • Auxiliary Space: O(N) 
Comment