Find Median from Data Stream

HardHeaps

Build a MedianFinder class that takes numbers one at a time and can report the median of everything it has seen so far, with two methods:

addNum(num) adds num. findMedian() returns the median: the middle value once the numbers are sorted, or the average of the two middle values when there is an even count of them (so 1, 2, 4, 8 gives 3).

Each test makes a new MedianFinder and calls its methods in order. The output lists what each call returns, with null for the constructor and for addNum.

Examples

Example 1
Input:  MedianFinder(), addNum(5), addNum(1), findMedian(), addNum(9), findMedian()
Output: [null, null, null, 3, null, 5]

With 1 and 5 the median is their average, 3. Adding 9 makes 1, 5, 9, whose middle is 5.

Example 2
Input:  MedianFinder(), addNum(-4), findMedian()
Output: [null, null, -4]

One number is its own median.

Constraints

  • -10⁵ ≤ num ≤ 10⁵
  • findMedian is only called after at least one addNum.
  • At most 5 × 10⁴ calls in all.

Stuck?

Hint 1

You never need the numbers fully sorted, only the two in the middle. Split them into a lower half and an upper half.

Hint 2

Keep the lower half in a max-heap and the upper half in a min-heap, with sizes equal or the lower one larger by one. Their tops are the middle values.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 8 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur