☰ All problems

51. Find Median from Data Stream

HardHeapDesignSorting

The median of a list of numbers is the middle value once the list is sorted. If the list has an even length, it is the average of the two middle values: the median of [2, 5, 9] is 5, and the median of [2, 5] is 3.5.

Design a structure that receives integers one at a time and can report the median of everything seen so far. Implement the MedianFinder class:

  • MedianFinder() creates an empty structure.
  • addNum(num) adds the integer num.
  • findMedian() returns the median of all numbers added so far, as a floating-point value.

Tests call the methods in sequence. findMedian is only called after at least one addNum. Answers within 10^-5 of the expected value are accepted.

Example 1
Input: ["MedianFinder","addNum","addNum","findMedian","addNum","findMedian"]
[[],[5],[2],[],[9],[]]
Output: [null,null,null,3.5,null,5]

Explanation: After adding 5 and 2, the sorted list is [2, 5] with median 3.5. After adding 9 it is [2, 5, 9] with median 5.

Constraints

  • -2^31 <= num <= 2^31 - 1
  • At least one number is added before any findMedian call
  • At most 5 * 10^4 calls in total

Follow-up: If every number in the stream is between 0 and 100, how could you make both operations O(1)? What if 99% of them are in that range?

💡 Hint 1

Keeping a sorted array makes findMedian O(1) but each insertion O(n). You only ever need the one or two values in the middle.

💡 Hint 2

Split the numbers into a lower half and an upper half. The median depends only on the largest value of the lower half and the smallest of the upper half.

💡 Hint 3

Store the lower half in a max-heap and the upper half in a min-heap, and rebalance after each insert so the lower half has the same size as the upper half or one more. (In Java, widen to long before adding the two tops: two large ints can overflow.)

class MedianFinder {
  constructor() {

  }

  /** @param {number} num */
  addNum(num) {

  }

  /** @return {number} */
  findMedian() {

  }
}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc