Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in C++: Two Heaps with priority_queue

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

    C++ · HEAP

    Find Median From Data Stream in C++, explained

    Problem overview

    The class MedianFinder keeps a growing collection of integers. addNum(num) adds one number, and findMedian() returns the median of everything added so far as a double. The median is the middle value of the sorted numbers, or the mean of the two middle values when the count is even. A number added twice counts twice.

    After adding 1 and 2, the median is 1.5. After adding 3 as well, the sorted numbers are [1, 2, 3] and the median is 2. With the stream 5, -3, -3, 10, the medians after each addition are 5, 1, -3 and 1.

    The budget is O(log n) for addNum and O(1) for findMedian, with up to 500,000 calls in total.

    Approach: two halves, two heaps

    The simplest design stores the numbers in a vector and sorts it for every question. That costs O(n log n) per call to findMedian, far too slow. Keeping the vector sorted by inserting each number in place costs O(n) per insertion, because the elements after it must shift.

    The median only depends on the middle of the sorted data, so there is no need to keep all of it sorted. Split the numbers into two halves:

    • low, the smaller half, in a max-heap: its top is the largest of the small numbers;
    • high, the larger half, in a min-heap: its top is the smallest of the large numbers.

    Every value in high is at least every value in low, so the two tops are exactly the two numbers next to the middle. The code keeps the halves the same size, or low one bigger. With an odd count, the median is the top of low. With an even count, it is the mean of both tops. Reading a top takes O(1), and each push or pop takes O(log n).

    Here is the state after each number of the stream 5, 1, 9, 7, 3:

    add 5: low top=5 size=1, high top=none size=0, median=5
    add 1: low top=1 size=1, high top=5 size=1, median=3
    add 9: low top=5 size=2, high top=9 size=1, median=5
    add 7: low top=5 size=2, high top=7 size=2, median=6
    add 3: low top=5 size=3, high top=7 size=2, median=5
    

    After the second number, low holds 1 and high holds 5, and the median is their mean, 3. After the fifth number, the sorted numbers are 1, 3, 5, 7, 9: low holds 1, 3 and 5, and high holds 7 and 9, so the median is the top of low, 5.

    Step by step

    1. Declare low as a priority_queue<int>. The C++ priority queue is a max-heap by default, which is what the lower half needs.
    2. Declare high as priority_queue<int, vector<int>, greater<int>>. The second argument is the container that stores the values, and greater<int> reverses the order so the smallest value sits on top.
    3. Push the new number into low. Every number enters the lower half first, whatever its size. The next lines restore the order between the halves.
    4. Move the top of low into high: push low.top(), then pop. In C++, top() only reads and pop() only removes, so a move takes both. The value that moves is the largest in low, so everything left in low is at most as large as it, and it joins high. A new number that is bigger than everything in high makes this round trip at once and lands in high. Either way, every value in high is still at least every value in low.
    5. Check the balance. If high now holds more values than low, the halves are lopsided.
    6. Move the top of high back into low in the same way. The halves are the same size again, or low is one bigger.
    7. In findMedian, handle the odd count: when low holds more values, return low.top().
    8. Handle the even count: the halves have equal size, so return the sum of both tops divided by 2.0.

    The solution in C++

    class MedianFinder {
    public:
        priority_queue<int> low;
        priority_queue<int, vector<int>, greater<int>> high;
    
        void addNum(int num) {
            low.push(num);
            high.push(low.top());
            low.pop();
            if (high.size() > low.size()) {
                low.push(high.top());
                high.pop();
            }
        }
    
        double findMedian() {
            if (low.size() > high.size()) {
                return low.top();
            }
            return (low.top() + high.top()) / 2.0;
        }
    };
    

    The C++ details worth a closer look:

    • Heap direction. priority_queue puts the largest element on top by default. For a min-heap, pass the container type and greater<int>. Forgetting the comparator is a common bug: priority_queue<int> high would give a second max-heap.
    • top() and pop() are separate. pop() returns void. Call top() first, and never on an empty heap, which is undefined behaviour.
    • Why top() is safe here. In addNum, low has just received a number, so it isn't empty. In findMedian, at least one number has been added, so low is never empty. The even branch also reads high.top(), and the halves have the same size there, so high has at least one value.
    • Dividing by 2.0. Integer division truncates: (1 + 2) / 2 is 1, while (1 + 2) / 2.0 is 1.5. The 2.0 makes the whole division a double.
    • The sum can't overflow. Values stay within 100,000 in absolute value, so the sum of two tops fits in an int easily. With values near the limits of int, adding two tops could overflow, and the sum would have to be computed as a double or long long.
    • The return type. return low.top(); converts an int to double automatically. A median of 2 comes back as 2.0, although std::cout prints a whole-number double as 2 unless you set its formatting.
    • Fields. The class has no constructor, so the compiler's default one creates two empty heaps, which is the "holds no numbers yet" state.

    Complexity

    Let n be the number of values added so far.

    addNum: O(log n). It does at most two pushes and two pops, in heaps that together hold n values. Each such operation costs O(log n).

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

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

    Edge cases and common mistakes

    • A single number. After addNum(5), low holds 5 and high is empty, so the odd branch returns 5 and never touches high.top().
    • Duplicates. The stream 5, -3, -3 has the median -3, since both copies are stored. Heaps keep duplicates, and the two heaps simply hold equal values on each side.
    • Negative numbers. Nothing in the design depends on the sign. The stream 5, -3, -3, 10 gives medians 5, 1, -3 and 1.
    • Asking twice. findMedian only reads the tops, so calling it twice returns the same value.
    • Integer division. Writing / 2 instead of / 2.0 turns 1.5 into 1 and 3.5 into 3.
    • Letting the halves drift apart. If the size check is missing, high can grow larger than low and the tops are no longer the middle values.
    • Pushing straight into the "right" half. Comparing num with the tops and choosing a heap works too, but it needs more cases. Pushing into low, moving its top to high and rebalancing handles every case with the same code.
    • Sorting on every query. It is correct but costs O(n log n) per call, which is too slow for 500,000 operations.

    Testing

    • Add 1, 2 and ask: 1.5. Add 3 and ask: 2.
    • Add 5 and ask: 5. Add -3 and ask: 1. Add -3 and ask: -3. Add 10 and ask: 1.
    • Add 4 and 3, ask twice: 3.5 both times. Add 2 and 1 and ask: 2.5.
    • Add 100000 twice and ask: 100000. Add -100000 and ask: 100000.
    • Add the numbers 0 to 999, repeated 500 times (500,000 additions), and ask: 499.5.
    Keep going with C++1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free