Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in Swift: 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

    SWIFT · HEAP

    Find Median From Data Stream in Swift, 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, and 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 class MedianFinder receives numbers one at a time and answers questions in between. addNum(_ num: Int) adds an integer, and findMedian() -> Double returns the median of everything added so far. findMedian is only called after at least one addNum, and it changes nothing, so asking twice gives the same answer.

    Example: after addNum(1) and addNum(2), the median is 1.5. After addNum(3) the numbers are [1, 2, 3] and the median is 2.0. A number that arrives twice counts twice: after 5, -3 and -3 the sorted numbers are [-3, -3, 5] and the median is -3.0.

    The statement asks for addNum in O(log n) time and findMedian in O(1) time.

    Approach: two heaps around the middle

    The simplest approach keeps all numbers in an array and sorts it for each question, which costs O(n log n) per call to findMedian. Inserting each number into its place in a sorted array is O(n) because the later elements shift. Neither meets the budget.

    The median depends only on the middle one or two values, so the data structure only needs quick access to those. Split the sorted numbers into two halves:

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

    The two middle values are then exactly the two tops. A heap gives its top in O(1) and inserts or removes in O(log n), which matches the budget.

    The halves must obey two rules after every addNum: every value in high is at least every value in low, and the sizes are equal or low has exactly one more. With these rules, an odd count has its median at the top of low, and an even count has it between the two tops.

    Keeping the rules takes three moves. Insert the new number into low. Then move the largest value of low into high. Whatever the new number was, the value that leaves low is its largest, so everything in high stays at least everything in low. Finally, if high now holds more values than low, move its smallest value back. Each move is one heap insert and one extract, so adding a number costs O(log n).

    Here is the state after each call on the numbers 5, -3, -3, 10, 7, 1:

    added  median  low size  high size  low top  high top
    5      5.0     1         0          5        -
    -3     1.0     1         1          -3       5
    -3     -3.0    2         1          -3       5
    10     1.0     2         2          -3       5
    7      5.0     3         2          5        7
    1      3.0     3         3          1        5
    

    Step by step

    1. Declare low as var low = MaxHeap(), the lower half. The lesson provides ready-to-use MaxHeap and MinHeap structs with insert(_:), extract(), peek(), count and isEmpty. They are structs whose methods change them, so the properties must be var.
    2. Declare high as var high = MinHeap(), the upper half.
    3. In addNum, insert num into low. Every new number goes into the lower half first, and the next lines restore the order.
    4. Move the largest value of low into high in one line: extract() removes and returns the top of low, and insert puts it into high.
    5. Rebalance. If high.count > low.count, move the smallest value of high back into low. This keeps the sizes equal, or low one larger.
    6. In findMedian, handle the odd case. If low holds more values than high, its top is the middle value, so return Double(low.peek()). Swift never converts an Int to a Double on its own.
    7. Handle the even case. Both halves have the same size, so return the sum of the two tops, converted to Double, divided by 2.

    The solution in Swift

    class MedianFinder {
        var low = MaxHeap()
        var high = MinHeap()
    
        func addNum(_ num: Int) {
            low.insert(num)
            high.insert(low.extract())
            if high.count > low.count {
                low.insert(high.extract())
            }
        }
    
        func findMedian() -> Double {
            if low.count > high.count {
                return Double(low.peek())
            }
            return Double(low.peek() + high.peek()) / 2
        }
    }
    

    The Swift details worth a closer look:

    • var for the heaps. The heaps are value types (structs), and insert and extract are mutating methods. With let low = MaxHeap(), the call low.insert(n) fails to compile with cannot use mutating member on immutable value: 'low' is a 'let' constant. MedianFinder is a class, so its methods can change its var properties without being marked mutating.
    • No automatic conversion to Double. Returning an Int from a function declared to return Double is a compile error: cannot convert return expression of type 'Int' to return type 'Double'. That is why both returns use Double(...).
    • Convert before dividing. Double(low.peek() + high.peek()) / 2 divides a Double by 2, which gives 2.5 for a sum of 5. Writing Double((low.peek() + high.peek()) / 2) divides the Int sum first, and integer division in Swift truncates toward zero: Double(7 / 2) is 3.0, while Double(7) / 2 is 3.5.
    • The literal 2 adapts. In Double(...) / 2, the literal 2 is read as a Double, so no conversion is needed for it.
    • Method calls in arguments. high.insert(low.extract()) first runs low.extract(), which changes low and returns its top, and then inserts that value into high. The two calls touch different properties, so there is no conflict.

    Complexity

    addNum: O(log n). It performs at most two inserts and two extracts on heaps of at most n values, and each one is O(log n).

    findMedian: O(1). It reads the top of one or both heaps and does one addition and one division.

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

    Edge cases and common mistakes

    • A single number. After addNum(5), the number moves to high and back to low, so low holds it and high is empty. findMedian returns 5.0 without touching high, which is why the odd case must come first. Calling high.peek() on an empty heap would be an error.
    • Duplicates. After 5, -3 and -3 the median is -3.0. Both heaps keep every copy.
    • Even counts. After 2 and 3 the median is 2.5, and after 4, 3, 2 and 1 it is 2.5 as well.
    • Not sorted input. Numbers can arrive in any order. The three-move routine handles each one the same way, whether it is a new smallest, a new largest or in between.
    • Asking twice. findMedian only reads the heaps, so repeating the call gives the same value. After 4 and 3, two calls both give 3.5.
    • Letting high grow larger than low. The odd case reads low.peek(), which is only right if low is the larger half. The rebalancing if guarantees it.
    • Integer division. Dividing the integer sum by 2 before converting loses the half.

    Testing

    • addNum(1), addNum(2), findMedian() gives 1.5. After addNum(3), findMedian() gives 2.0.
    • addNum(5), findMedian() gives 5.0. Then addNum(-3) gives 1.0, a second addNum(-3) gives -3.0, and addNum(10) gives 1.0.
    • addNum(4), addNum(3), then two findMedian() calls give 3.5 and 3.5. After addNum(2) and addNum(1) it gives 2.5.
    • Adding 100000 twice gives 100000.0.
    Keep going with Swift1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free