VOOZH about

URL: https://www.geeksforgeeks.org/dsa/median-of-stream-of-running-integers-using-stl-set-2/

⇱ Median of Stream of Running Integers using STL | Set 2 - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Median of Stream of Running Integers using STL | Set 2

Last Updated : 23 Jul, 2025

Given an array arr[] of size N representing integers required to be read as a data stream, the task is to calculate and print the median after reading every integer.

Examples:

Input: arr[] = { 5, 10, 15 } Output: 5 7.5 10 Explanation: After reading arr[0] from the data stream, the median is 5. After reading arr[1] from the data stream, the median is 7.5. After reading arr[2] from the data stream, the median is 10.

Input: arr[] = { 1, 2, 3, 4 } Output: 1 1.5 2 2.5

Approach: The problem can be solved using Ordered Set. Follow the steps below to solve the problem:

  • Initialize a multi Ordered Set say, mst to store the array elements in a sorted order.
  • Traverse the array using variable i. For every ith element insert arr[i] into mst and check if the variable i is even or not. If found to be true then print the median using (*mst.find_by_order(i / 2)).
  • Otherwise, print the median by taking the average of (*mst.find_by_order(i / 2)) and (*mst.find_by_order((i + 1) / 2)).

Below is the implementation of the above approach:


Output
1 1.5 2 2.5 3 

Time Complexity: O(N * log(N)) 
Auxiliary Space: O(N)

Comment