Practice · Heap · 5 of 5

Running Median

Write a class MedianFinder that collects integers and reports their median:

  • addNum(num) adds num to the collection.
  • findMedian() returns the median of every number added so far.

The median is the middle value once the numbers are sorted. With an even count there are two middle values, and the median is their average, so the median of [2, 3] is 2.5. findMedian is only called after at least one number has been added. Aim for O(log n) per addNum and O(1) per findMedian.

Each test is a list of calls, starting with the constructor; the expected answer lists what each call returns (null for the constructor and for addNum). A median within 10⁻⁵ of the right value is accepted.

Example 1

Calls
MedianFinder(), addNum(4), addNum(10), findMedian(), addNum(6), findMedian()
Returns
[null, null, null, 7, null, 6]
After 4 and 10 the median is their average, 7. Adding 6 makes it the middle value.

Example 2

Calls
MedianFinder(), addNum(5), findMedian(), addNum(-4), addNum(10), findMedian(), addNum(0), findMedian()
Returns
[null, null, 5, null, null, 5, null, 2.5]
Sorted, the last collection is −4, 0, 5, 10, so the median is the average of 0 and 5.

Constraints

  • Every number is between −10⁵ and 10⁵.
  • A test makes at most 5 × 10⁴ calls.
Brush up firstHeap visualiser