Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in Scala: 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 7
    Ctrl + Enter to check

    SCALA · HEAP

    Find Median From Data Stream in Scala, explained

    Problem overview

    The median of a list of numbers is the middle value once the list is sorted. With an even number of values there is no single middle, so the median is the mean of the two middle values: the median of [2, 3, 4] is 3 and the median of [2, 3] is 2.5.

    The lesson asks for a class MedianFinder with two methods. addNum(num) takes an Int and stores it. findMedian() returns the median of every number added so far, as a Double. It is only called after at least one number has been added.

    In the first example, after adding 1 and 2 the median is 1.5, and after adding 3 as well it is 2.0. In the second, adding 5, -3, -3 and 10 gives the medians 5.0, 1.0, -3.0 and 1.0: a number that arrives twice counts twice. The statement asks for addNum in O(log n) time and findMedian in O(1).

    Approach: the middle sits at the top of two heaps

    The simple idea keeps a list and sorts it whenever the median is requested. That costs O(n log n) per question. Inserting into an already sorted array avoids the sort, but shifting elements makes each insertion O(n).

    The lesson takes a different route. The median depends only on the values around the middle, so it splits the numbers into two halves:

    • low holds the smaller half in a max-heap, whose top is its largest value;
    • high holds the larger half in a min-heap, whose top is its smallest value.

    Every value in high is at least every value in low, so the two middle values of the whole collection are always the two tops. The halves are kept the same size, or with low exactly one larger. Then an odd count has its middle value on top of low, and an even count has its two middle values on top of the two heaps.

    Adding a number needs two heap moves to keep both rules true. The new number goes into low first. Then the largest value of low moves to high, which guarantees that nothing in high is smaller than anything in low, whatever the new number was. If that left high with more values than low, the smallest value of high moves back. Each heap operation costs O(log n), and reading a top is O(1).

    Here is the state after adding 5, -3, -3 and 10 in turn, with the tops of both heaps:

    addedtop of lowsize of lowtop of highsize of highmedian
    551none05.0
    -3-31511.0
    -3-3251-3.0
    10-32521.0

    Step by step

    1. Declare low. PriorityQueue[Int]() in a val. Scala's mutable PriorityQueue is a max-heap by default, which is what the lower half needs.
    2. Declare high. The same type with a second pair of parentheses holding Ordering[Int].reverse. Reversing the ordering makes the smallest number count as the largest, so the smallest sits on top.
    3. In addNum, enqueue the number into low. Every new number enters the lower half first.
    4. Move the top of low to high. low.dequeue() removes and returns the largest value in low, and high.enqueue(...) receives it in the same line.
    5. Rebalance. If high.size exceeds low.size, the smallest value of high goes back into low. After this step the sizes are equal, or low has one more.
    6. In findMedian, handle the odd case. When low holds more values than high, the count is odd and low.head, the top of low, is the median. head reads the top without removing it, and toDouble makes the return type fit.
    7. Handle the even case. The sizes are equal, so the median is the sum of the two tops divided by 2.0.

    The solution in Scala

    class MedianFinder {
        val low = PriorityQueue[Int]()
        val high = PriorityQueue[Int]()(Ordering[Int].reverse)
    
        def addNum(num: Int): Unit = {
            low.enqueue(num)
            high.enqueue(low.dequeue())
            if (high.size > low.size) {
                low.enqueue(high.dequeue())
            }
        }
    
        def findMedian(): Double = {
            if (low.size > high.size) {
                return low.head.toDouble
            }
            return (low.head + high.head) / 2.0
        }
    }
    

    The lesson's file already imports scala.collection.mutable.PriorityQueue; in a program of your own, add that import. The Scala details worth a closer look:

    • Max-heap by default. PriorityQueue[Int]() uses the natural ordering of Int and puts the largest element at head. For enqueue(3, 9, 1) the head is 9. The reversed queue holds the same values with 1 at its head.
    • The second parameter list. The constructor takes its Ordering in a separate parameter list, which is why the code reads PriorityQueue[Int]()(Ordering[Int].reverse). The first () holds the optional initial elements, and the second holds the ordering.
    • head is not dequeue(). head only reads the top. dequeue() removes it. The problem guarantees that findMedian comes after at least one addNum, so there is always a top to read.
    • Integer division versus 2.0. 3 / 2 is the Int 1, but 3 / 2.0 is the Double 1.5. Dividing the sum by 2.0 keeps the half.
    • Int addition happens first. low.head + high.head is an Int sum, and only the division is done in Double. With values in the problem's range of plus or minus 100,000 the sum cannot overflow. With Int values near the limit it would wrap: two copies of 2000000000 give -1.47483648E8.
    • Printing. println(2.0) prints 2.0 in Scala, which matches the one-digit format the lesson's output uses.

    Complexity

    Time. addNum performs three heap operations (an enqueue, a dequeue and an enqueue), plus one more dequeue and enqueue when it rebalances: at most five in all. Each costs O(log n), so addNum is O(log n). findMedian reads one or two tops and does one division, so it is O(1).

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

    Edge cases and common mistakes

    • One number. After addNum(5) the number moves from low to high and straight back, so low holds it and the median is 5.0.
    • Duplicates. Adding -3 twice stores two copies, and the median counts both: after 5, -3, -3 it is -3.0.
    • Calling findMedian twice. It changes nothing, so asking twice gives the same answer: after adding 4 and 3, both calls return 3.5.
    • Numbers out of order. Adding 4, 3, 2, 1 gives 3.5 after the first two numbers and 2.5 after all four. The heaps do not care about the arrival order.
    • Letting the sizes drift. If low were allowed to grow two values bigger than high, the middle values would no longer sit at the tops. The rebalancing step prevents that.
    • Using the same ordering for both heaps. Two max-heaps would put the largest values on top of both, and high.head would not be the smallest of the upper half.
    • Integer division. Writing / 2 instead of / 2.0 would turn 1.5 into 1.

    Testing

    • addNum(1), addNum(2), findMedian() gives 1.5. After addNum(3), findMedian() gives 2.0.
    • Adding 5, -3, -3, 10, with findMedian() after each, gives 5.0, 1.0, -3.0, 1.0.
    • Adding 4 and 3 gives 3.5, twice in a row. Then adding 2 and 1 gives 2.5.
    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free