[Geeks for Geeks] Find median in a stream

Find median in a stream

Given an input stream of N integers. The task is to insert these numbers into a new stream and find the median of the stream formed by each insertion of X to the new stream.

  • Time : O(logn)
  • Space : O(n)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution
{
priority_queue<int> left;
priority_queue<int, vector<int>, greater<int>> right;
public:
//Function to insert heap.
void insertHeap(int &x)
{
right.push(x);
if(right.size() > left.size()) {
left.push(right.top());
right.pop();
}

if(!left.empty() and !right.empty() and left.top() > right.top()) {
auto l = left.top(); left.pop();
auto r = right.top(); right.pop();
left.push(r); right.push(l);
}
}

//Function to return Median.
double getMedian()
{
int sz = left.size() + right.size();
if(sz == 0) return -1;
if(sz & 1)
return left.top();
return (left.top() + right.top()) / 2.0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/15/PS/GeeksforGeeks/find-median-in-a-stream/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.