231. Find Median in a Stream

You are given a stream of integers arr[], arriving one by one. After each new integer is added to the stream, output the median of all elements seen so far.

Return a list of medians — one after each insertion — where:

  • If the number of elements is odd, the middle element is the median.
  • If the number of elements is even, the average of the two middle elements is the median.

Example 1:

Input: arr = [5, 15, 1, 3, 2, 8]

Output: [5.0, 10.0, 5.0, 4.0, 3.0, 4.0]

Explanation:

  • After inserting 5 → median = 5.0
  • After inserting 15 → median = (5 + 15) / 2 = 10.0
  • After inserting 1 → median = 5.0
  • After inserting 3 → median = (3 + 5) / 2 = 4.0
  • After inserting 2 → median = 3.0
  • After inserting 8 → median = (3 + 5) / 2 = 4.0

Example 2:

Input: arr = [2, 2, 2, 2]

Output: [2.0, 2.0, 2.0, 2.0]

Explanation: All values are equal, so median remains 2.0 throughout.

Now Your Turn!

Pick the correct output for the given input

Input: arr = [1, 3, 5, 7, 9]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= arr.length <= 105
  • 1 <= arr[i] <= 106
  • You must return the median after every insertion, in O(log N) time per insertion.

Fun Facts

0
class Solution {
public:
vector<double> getMedian(vector<int> &arr) {
// Your code goes here
}
};
Test Case

Input:

Arr