Find Median from Data Stream

Hard#295two heaps

Build a class that gets numbers one at a time with addNum and, whenever findMedian is called, returns the median of all the numbers so far: the middle one for an odd count, the average of the two middle ones for an even count. Our example: addNum(5), addNum(8), findMedian(), addNum(2), addNum(1), findMedian(), addNum(9), findMedian() — the medians are 6.5, 3.5 and 5.

input
Calls one after another: MedianFinder() starts with no numbers, then addNum(num) adds one and findMedian() asks for the median of those added so far.
returns
findMedian(): the middle number of those added, in sorted order; with an even count, the mean of the two middle ones. Within 10⁻⁵ counts. addNum returns nothing (null in the output).
constraints
  • 2 ≤ calls ≤ 2000
  • −10⁵ ≤ num ≤ 10⁵
  • findMedian is called only after a number is added
our 8 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
var MedianFinder = function() {

};

/**
 * @param {number} num
 * @return {void}
 */
MedianFinder.prototype.addNum = function(num) {

};

/**
 * @return {number}
 */
MedianFinder.prototype.findMedian = function() {

};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * var obj = new MedianFinder()
 * obj.addNum(num)
 * var param_2 = obj.findMedian()
 */
Ctrl ↵
format
reset

saved in this browser

8 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more heap and top k problems

Pattern “Heap and top K” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.