Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in TypeScript: Two Heaps

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

    TYPESCRIPT · HEAP

    Find Median From Data Stream in TypeScript, 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 class MedianFinder receives numbers one at a time through addNum(num), and findMedian() must return the median of everything added so far. It can be asked at any moment, as often as needed, and asking changes nothing. For the calls addNum(1), addNum(2), findMedian(), addNum(3), findMedian() the answers are 1.5 and 2.

    Approach

    The simple way is to keep an array and sort it before every question, which costs O(n log n) per call. Keeping the array sorted with insertions still moves up to n values each time. The statement asks for addNum in O(log n) and findMedian in O(1).

    The median depends only on the middle of the sorted data, so the code splits the numbers into two halves:

    • the lower half in a max-heap, whose top is its largest value;
    • the upper half in a min-heap, whose top is its smallest value.

    Every value in the upper half is at least every value in the lower half, and the halves have the same size or the lower half has one more. Then the middle of the sorted data sits at the two tops: with an odd count the top of the lower half is the median, and with an even count the median is the mean of the two tops. Reading a top is O(1), and inserting into or removing from a heap is O(log n).

    The lesson provides ready-to-use MaxHeap and MinHeap classes with insert(value), extract() (removes and returns the top), peek() (reads the top), size() and isEmpty().

    Step by step

    1. The lower half. A field low of type MaxHeap, set to new MaxHeap().
    2. The upper half. A field high of type MinHeap, set to new MinHeap().
    3. Insert into the lower half first. Every new number goes into this.low, whatever its size.
    4. Move the lower half's largest value up. this.low.extract() removes and returns it, and it is inserted into this.high. Whatever num was, the value that leaves low is its largest, so every value in high stays at least every value in low. If num was the largest, it is simply the one that moves.
    5. Rebalance. After step 4, high may have one value more than low. In that case its smallest value moves back to low. The halves then differ in size by at most one, with low never smaller.
    6. Odd count. In findMedian, if low holds more values than high, it has exactly one more, so its top is the middle value: this.low.peek().
    7. Even count. Otherwise the halves are equal, and the median is the mean of the two tops, (this.low.peek() + this.high.peek()) / 2.

    The solution in TypeScript

    class MedianFinder {
        low: MaxHeap = new MaxHeap();
        high: MinHeap = new MinHeap();
        addNum(num: number): void {
            this.low.insert(num);
            this.high.insert(this.low.extract());
            if (this.high.size() > this.low.size()) {
                this.low.insert(this.high.extract());
            }
        }
        findMedian(): number {
            if (this.low.size() > this.high.size()) {
                return this.low.peek();
            }
            return (this.low.peek() + this.high.peek()) / 2;
        }
    }
    

    Details for TypeScript:

    • Field initializers. low: MaxHeap = new MaxHeap(); declares the field and gives it a value when each MedianFinder is created, so no constructor is needed and every instance gets its own heaps.
    • / 2 keeps the fraction. In TypeScript every number is a double, so (1 + 2) / 2 is 1.5, with no integer division to work around. Because of that, a median that is a whole number comes back as 2, not 2.0; the number is the same, and only the printed form differs.

    Walking through an example

    For the numbers 5, -3, -3, 10, each call to addNum leaves the heaps like this:

    AddedTop of lowTop of highSizes (low, high)Median
    55none1, 05
    -3-351, 11
    -3-352, 1-3
    10-352, 21

    A number that arrives twice is stored twice, which is why the third row has two values in low and the median is -3.

    Complexity

    addNum: O(log n). It does at most three heap operations on heaps that hold about n / 2 values each. findMedian: O(1). It reads one or two tops. Space: O(n). Every added number is stored once.

    Edge cases and common mistakes

    • One number. After addNum(5), low holds 5 and high is empty, so the odd branch returns 5. The even branch is never reached with an empty high, because the problem calls findMedian only after at least one addNum.
    • Duplicates. Equal values are separate entries and both count.
    • Negative numbers. Nothing in the code depends on the sign. -3 and 5 give a median of 1.
    • Asking twice. findMedian only reads, so two calls in a row give the same answer.
    • Skipping the "up, then down" moves. Inserting straight into the right heap needs a comparison with the tops and special cases for empty heaps. Pushing through low into high keeps the ordering rule without any of that.
    • Letting the sizes drift. If high were allowed to grow larger than low, the middle would no longer sit at the tops.

    Testing

    CallsMedians returned
    add 1, add 2, find, add 3, find1.5, 2
    add 5, find, add -3, find, add -3, find, add 10, find5, 1, -3, 1
    add 4, add 3, find, find, add 2, add 1, find3.5, 3.5, 2.5
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free