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:
C++
// C++ program to implement// the above approach #include <iostream>#include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std;typedef tree<int, null_type, less_equal<int>, rb_tree_tag,tree_order_statistics_node_update> idxmst; // Function to find the median// of running integersvoid findMedian(int arr[], int N){ // Initialise a multi ordered set // to store the array elements // in sorted order idxmst mst; // Traverse the array for (int i = 0; i < N; i++) { // Insert arr[i] into mst mst.insert(arr[i]); // If i is an odd number if (i % 2 != 0) { // Stores the first middle // element of mst double res = *mst.find_by_order(i / 2); // Stores the second middle // element of mst double res1 = *mst.find_by_order( (i + 1) / 2); cout<< (res + res1) / 2.0<<" "; } else { // Stores middle element of mst double res = *mst.find_by_order(i / 2); // Print median cout << res << " "; } }} // Driver Codeint main(){ // Given stream of integers int arr[] = { 1, 2, 3, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); // Function call findMedian(arr, N);} |
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


