Start learning free

LESSON 458 OF 671 · HEAP

Find Median from Data Stream in JavaScript: Two Heaps, O(log n) Insert

Practice O(log n) Read the full explanation

The median of a list of numbers is the middle value once the list is sorted. When the list has an even number of values, there is no single middle value, and the median is the mean of the two middle values:

  • the median of [2, 3, 4] is 3;
  • the median of [2, 3] is (2 + 3) / 2 = 2.5.

Numbers arrive one at a time, and at any moment you may be asked for the median of all the numbers that have arrived so far. Implement the class MedianFinder:

  • MedianFinder() creates an object that holds no numbers yet.
  • addNum(num) adds the integer num to the numbers seen so far.
  • findMedian() returns the median of all the numbers added so far.

The input is a list of operations, applied in order to one new MedianFinder. The output lists what the findMedian calls return, in order, each printed with one digit after the decimal point (2.0, 2.5). The starter code spells these names the way your language does.

 

Example 1:

Input:
    addNum(1)
    addNum(2)
    findMedian()
    addNum(3)
    findMedian()
Output: 1.5 2.0
Explanation:
After 1 and 2, there are two middle values, so the median is (1 + 2) / 2 = 1.5.
After 3 arrives, the sorted numbers are [1, 2, 3], and the middle one is 2.

Example 2:

Input:
    addNum(5)
    findMedian()
    addNum(-3)
    findMedian()
    addNum(-3)
    findMedian()
    addNum(10)
    findMedian()
Output: 5.0 1.0 -3.0 1.0
Explanation:
[5] has the median 5. [-3, 5] has the median (-3 + 5) / 2 = 1.
[-3, -3, 5] has the median -3: a number that arrives twice counts twice.
[-3, -3, 5, 10] has the median (-3 + 5) / 2 = 1.

Example 3:

Input:
    addNum(4)
    addNum(3)
    findMedian()
    findMedian()
    addNum(2)
    addNum(1)
    findMedian()
Output: 3.5 3.5 2.5
Explanation: The numbers don't arrive in sorted order, and asking twice in a row gives the same answer, because findMedian changes nothing. At the end the sorted numbers are [1, 2, 3, 4], so the median is (2 + 3) / 2 = 2.5.

 

Constraints:

  • -105 <= num <= 105
  • findMedian is called only after at least one call to addNum.
  • At most 5 * 105 calls in total are made to addNum and findMedian.

Note:

addNum should run in O(log n) time and findMedian in O(1) time, where n is the number of values added so far.

STEP 1 OF 7
    Ctrl + Enter to check

    JAVASCRIPT · HEAP

    Find Median From Data Stream in JavaScript, explained

    Problem overview

    The median of a list is its middle value once the list is sorted. With an even number of values it is the mean of the two middle ones: the median of [2, 3, 4] is 3, and the median of [2, 3] is 2.5.

    The task is to implement a class MedianFinder. Numbers arrive one at a time through addNum(num), and findMedian() returns the median of everything added so far. A number that arrives twice counts twice, and findMedian is only called after at least one number has been added.

    For example, after addNum(5), addNum(-3), addNum(-3) and addNum(10), the successive medians are 5, 1, -3 and 1. The statement asks for O(log n) time for addNum and O(1) time for findMedian.

    Approach: two halves, two heaps

    The simple solution keeps an array and sorts it for every question. That costs O(n log n) per findMedian, which is too slow with up to 500,000 calls. Keeping the array sorted as numbers arrive doesn't help much either, because inserting into the middle of an array shifts many elements.

    The median only depends on the middle one or two values, so the lesson keeps just enough order to find them. It splits the numbers into two halves:

    • low, a max-heap holding the smaller half. Its top is the largest value of that half.
    • high, a min-heap holding the larger half. Its top is the smallest value of that half.

    Every value in high is at least every value in low, so the two middle values of the whole list are the two tops. The halves are kept balanced: the same size, or low one bigger. Then:

    • With an odd count, low holds one extra value, and its top is the median.
    • With an even count, the median is the mean of the two tops.

    Pushing to or popping from a heap costs O(log n), and reading the top costs O(1), which gives the budget the statement sets.

    Here is how the halves change as 5, 15, 1 and 3 arrive:

    addedsize of lowtop of lowsize of hightop of highfindMedian()
    5150none5
    151511510
    1251155
    323254

    Step by step

    1. Create this.low in the constructor as a MaxHeap from the algorithms library. JavaScript has no built-in heap, so the lesson uses this one. The lesson provides insert(value), extract(), peek() and the size n on its heaps.
    2. Create this.high as a MinHeap from the same place.
    3. In addNum, insert num into this.low first. Every new number starts in the lower half, and the next lines restore the order.
    4. Move the largest value of this.low into this.high: extract() removes and returns it, and insert puts it in the other heap. Whatever num was, the value that leaves the lower half is its largest, so everything in high stays at least everything in low.
    5. Rebalance. If high now has more values than low, move the smallest value of high back into low. The halves are then the same size, or low is one bigger.
    6. In findMedian, handle an odd count. If low has more values than high, its top, peek(), is the middle value.
    7. Otherwise the halves are equal, and the median is the sum of the two tops divided by 2.

    The solution in JavaScript

    var algorithms = require('algorithms')
    class MedianFinder {
        constructor() {
            this.low = new algorithms.DataStructures.Heap.MaxHeap();
            this.high = new algorithms.DataStructures.Heap.MinHeap();
        }
    
        addNum(num) {
            this.low.insert(num);
            this.high.insert(this.low.extract());
            if (this.high.n > this.low.n) {
                this.low.insert(this.high.extract());
            }
        }
    
        findMedian() {
            if (this.low.n > this.high.n) {
                return this.low.peek();
            }
            return (this.low.peek() + this.high.peek()) / 2;
        }
    }
    

    The JavaScript details worth a closer look:

    • require('algorithms'). This loads the heap library as a Node module. The heaps live under algorithms.DataStructures.Heap.
    • Fields on this. this.low and this.high belong to each MedianFinder instance, so two finders never share data.
    • n is a property, not a method. It is written this.low.n, without parentheses.
    • / keeps the fraction. In JavaScript every number is a double, so 7 / 2 is 3.5 and no conversion is needed. There is no separate integer type to cast to.
    • Whole medians are plain numbers. findMedian returns the number 2, not 2.0: JavaScript prints both the same way. Formatting with a decimal digit is a matter of how the result is displayed.

    The two-step insert looks roundabout, but it makes the code short and correct for every case. Inserting into low and then moving its top to high guarantees the order between the halves, and the single rebalance step guarantees the sizes. There are no cases to compare against the tops.

    Complexity

    addNum: O(log n). It does at most two inserts and two extracts, each O(log n) in a heap of up to n values.

    findMedian: O(1). It reads one or two tops and does one addition and one division.

    Space: O(n). Every number added is stored in one of the two heaps.

    Edge cases and common mistakes

    • A single number. After addNum(7), low holds 7 and high is empty, and the median is 7. The odd branch returns before high.peek() is needed.
    • Duplicates. 5, -3, -3 gives -3. Every copy is stored in a heap, so repeated numbers count each time.
    • Numbers out of order. Adding 4, 3, 2, 1 gives medians 4, 3.5, 3 and 2.5. The heaps handle any order.
    • Asking twice. findMedian only reads the tops, so repeating it gives the same answer.
    • Wrong sizes. If high were allowed to grow bigger than low, the odd branch would return the wrong half's top. The rebalance step prevents it.
    • Heaps the wrong way round. The lower half must be a max-heap and the upper half a min-heap. Swapping them puts the extremes of the whole list at the tops instead of the middle values.
    • Forgetting that the mean can be a fraction. The median of [1, 2] is 1.5, so the even branch must divide with / and not floor the result.

    Testing

    Medians returned by findMedian for these sequences of calls:

    • addNum(1), addNum(2), findMedian(), addNum(3), findMedian() gives 1.5 and then 2.
    • addNum(5), findMedian(), addNum(-3), findMedian(), addNum(-3), findMedian(), addNum(10), findMedian() gives 5, 1, -3 and 1.
    • addNum(4), addNum(3), findMedian(), findMedian(), addNum(2), addNum(1), findMedian() gives 3.5, 3.5 and 2.5.
    • addNum(7), findMedian() gives 7.
    Keep going with JavaScript650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free