Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in Go: Two Heaps, O(log n) Adds

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 8
    Ctrl + Enter to check

    GO · HEAP

    Find Median From Data Stream in Go, explained

    Problem overview

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

    The task is a type, MedianFinder, that receives integers one at a time and can be asked for the median of everything received so far. It has a Constructor that returns an empty finder, a method AddNum(num int) and a method FindMedian() float64. FindMedian is only called after at least one number was added, and up to 500,000 calls are made in total.

    Adding 5, -3, -3 and then 10, with a question after each number, gives medians 5.0, 1.0, -3.0 and 1.0. A number that arrives twice counts twice. The expected costs are O(log n) for AddNum and O(1) for FindMedian.

    Approach: two heaps around the middle

    The simplest design keeps every number in a slice and sorts it on every question. That costs O(n log n) per question, which is too slow for this many calls. Inserting each new number into its place in a sorted slice makes the question cheap but shifts elements on every insertion.

    The median only depends on the values in the middle, so there is no need to keep everything sorted. Split 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, so the middle of the sorted data sits at the two tops. Keep the halves the same size, or the lower half one bigger. Then, for an odd count, the median is the top of the lower half. For an even count, it is the mean of the two tops. A heap gives its top in O(1) and takes a push or a pop in O(log n), which matches the targets.

    The lesson provides the two heap types, maxHeap and minHeap. Both implement heap.Interface from the standard container/heap package, and index 0 of each holds its top.

    Step by step

    1. Add the lower half. The struct gets a field low of type maxHeap. Its Less is reversed, so the heap package keeps the largest value at index 0.
    2. Add the upper half. A field high of type minHeap keeps the smallest value at index 0.
    3. Write the constructor. It returns MedianFinder{}. Both fields start as empty (nil) slices, and append works on those, so no setup is needed.
    4. Push the new number into low with heap.Push(&this.low, num). The pointer is needed because pushing grows the slice.
    5. Move the largest of low into high. heap.Pop(&this.low) removes the top of low, and its result goes straight into heap.Push(&this.high, ...). Whatever num was, the value leaving low is its largest, so everything in high stays at least as large as everything in low.
    6. Rebalance. The previous step may have left high bigger. If this.high.Len() > this.low.Len(), move the smallest value of high back into low.
    7. Odd count. In FindMedian, when low holds more values than high, the top of low is the middle, and it is converted to float64.
    8. Even count. Otherwise both halves have the same size. Convert the sum of the two tops to float64 and divide by 2.

    The solution in Go

    type MedianFinder struct {
        low maxHeap
        high minHeap
    }
    
    func Constructor() MedianFinder {
        return MedianFinder{}
    }
    
    func (this *MedianFinder) AddNum(num int) {
        heap.Push(&this.low, num)
        heap.Push(&this.high, heap.Pop(&this.low))
        if this.high.Len() > this.low.Len() {
            heap.Push(&this.low, heap.Pop(&this.high))
        }
    }
    
    func (this *MedianFinder) FindMedian() float64 {
        if this.low.Len() > this.high.Len() {
            return float64(this.low[0])
        }
        return float64(this.low[0] + this.high[0]) / 2
    }
    

    Here is the state after each number of the sequence 5, -3, -3, 10, with the two tops and sizes of the halves:

    Addedlow top (size)high top (size)Median
    55 (1)empty (0)5.0
    -3-3 (1)5 (1)1.0
    -3-3 (2)5 (1)-3.0
    10-3 (2)5 (2)1.0

    Look at the second row. The number -3 goes into low next to 5, then 5, the largest, moves to high. The halves are balanced, with sizes 1 and 1. On the third row, the second -3 goes into low, and its largest value, -3, moves to high, which would make high bigger, so the smallest of high, -3, goes back. The net effect is that low gains the number and high is unchanged.

    The same finder, given 4, 3, 2, 1 with a question after each number, answers 4.0, 3.5, 3.0 and 2.5.

    Go details

    • heap.Push and heap.Pop take a pointer. They call the Push and Pop methods of heap.Interface, which have pointer receivers because they change the slice's length. That is why the code writes &this.low. A plain this.low would not compile, because maxHeap itself doesn't have those methods.
    • any in, any out. heap.Push takes its value as any, and heap.Pop returns any. Passing one's result straight into the other works without a type assertion, and passing the int num to heap.Push needs no conversion.
    • Reading the top is plain indexing. A heap is a slice underneath, and the heap package keeps the best value at index 0, so this.low[0] reads the top without removing it.
    • Convert before dividing. Go never converts between number types on its own, and integer division drops the fraction. With the two tops 2 and 3, (2 + 3) / 2 on integers gives 2, while float64(2 + 3) / 2 gives 2.5. In the solution, float64(this.low[0] + this.high[0]) / 2 converts the sum first, so the division is a float division.
    • The zero value is usable. MedianFinder{} has two nil slices, which are valid empty heaps. The pointer receiver on AddNum means calls on an addressable variable such as m := Constructor() change m itself.

    Complexity

    AddNum: O(log n). It does at most three pushes and two pops, each O(log n) in the size of the heap.

    FindMedian: O(1). It reads one or two array positions and does an addition and a division.

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

    Edge cases and common mistakes

    • One number. After AddNum(7), the number moves to high and straight back to low, so low holds it and the median is 7. The even-count branch is never reached with an empty high.
    • Duplicates. Equal values are stored separately and counted separately, so 5, -3, -3 gives a median of -3.0.
    • Extreme values. Adding 7, -100000 and 100000 gives a median of 7. The sum of two tops is at most 200,000 in size, which is no problem for int.
    • Asking twice. FindMedian doesn't change anything, so two calls in a row return the same value.
    • Dividing integers. Writing float64(this.low[0] + this.high[0] / 2) puts the parenthesis in the wrong place. The division then happens on integers, and for the tops 2 and 3 the result is 3.0 instead of 2.5.
    • Passing the heap by value. heap.Push(this.low, num) doesn't compile. Without a pointer, the slice would be a copy and the caller's heap would not grow.
    • Forgetting to rebalance. Without the last if, high would grow faster than low and the tops would no longer be the middle values.
    • Sorting on every question. It gives correct answers but is O(n log n) each time, which is too slow for 500,000 calls.

    Testing

    • Add 1, 2, ask, add 3, ask: 1.5 then 2.0.
    • Add 5, ask, add -3, ask, add -3, ask, add 10, ask: 5.0, 1.0, -3.0, 1.0.
    • Add 4, 3, ask twice, add 2, 1, ask: 3.5, 3.5, 2.5.
    • Add 7, ask: 7.0.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free