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 inputInput: 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.