Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in C#: Two Heaps with PriorityQueue

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

    You implement a class MedianFinder with two methods. AddNum(int num) adds a number to the collection, and FindMedian() returns the median of everything added so far as a double. The median is the middle value of the sorted numbers. With an even count there is no single middle value, so the median 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 calls come in any order, with at least one AddNum before the first FindMedian. For the calls AddNum(1), AddNum(2), FindMedian(), AddNum(3), FindMedian() the answers are 1.5 and 2.0. Duplicates count: after adding 5, -3 and -3 the sorted numbers are [-3, -3, 5] and the median is -3.

    The target is AddNum in O(log n) time and FindMedian in O(1) time, where n is how many numbers have been added.

    Approach: two halves, two heaps

    The simplest design keeps a list and sorts it for every question, which costs O(n log n) per FindMedian. Keeping the list sorted by inserting each number in its place avoids the sort, but shifting elements in a list still costs O(n) per insertion.

    The median only depends on the middle of the sorted order, so you don't need the whole order. Split the numbers into two halves: the lower half and the upper half. Every number in the lower half is at most every number in the upper half. The middle values are then the largest of the lower half and the smallest of the upper half. A max-heap gives instant access to the largest of the lower half, and a min-heap gives instant access to the smallest of the upper half. Reading the top of a heap is O(1), and adding or removing an element is O(log n).

    The halves must stay balanced. The lesson keeps the lower half equal in size to the upper half, or one larger. Then:

    • with an odd count, the lower half has one extra value, and its top is the median;
    • with an even count, the halves have the same size, and the median is the mean of the two tops.

    To add a number, push it into the lower half, then move that half's largest value to the upper half. This guarantees that every value in the upper half is at least every value in the lower half, whatever num was. After that the upper half may be one value too big, and if so, its smallest value moves back to the lower half. Each add does a constant number of heap operations.

    The run below adds 4, 3, 2, 1, 10 and -5 in turn and prints the two tops and sizes after each add, and the median:

    add 4: low top 4 (size 1), high top - (size 0)  median 4
    add 3: low top 3 (size 1), high top 4 (size 1)  median 3.5
    add 2: low top 3 (size 2), high top 4 (size 1)  median 3
    add 1: low top 2 (size 2), high top 3 (size 2)  median 2.5
    add 10: low top 3 (size 3), high top 4 (size 2)  median 3
    add -5: low top 2 (size 3), high top 3 (size 3)  median 2.5
    

    Step by step

    1. Declare low, the lower half, as a PriorityQueue<int, int> built with Comparer<int>.Create((x, y) => y - x). C#'s PriorityQueue is a min-heap: it hands out the element with the smallest priority first. The comparer reverses the order, so the largest priority comes out first, which makes low a max-heap.
    2. Declare high as a plain PriorityQueue<int, int>. It is a min-heap, the upper half.
    3. In AddNum, enqueue num into low, using num as both the element and its priority, so the heap orders the numbers themselves.
    4. Move the largest of low into high. Dequeue from low into largest, then enqueue it into high. Now every value in high is still at least every value in low.
    5. Rebalance. If high.Count > low.Count, the middle values are no longer at the tops.
    6. Move the smallest of high back to low the same way. The halves are now the same size, or low is one bigger.
    7. In FindMedian, handle an odd count. If low holds more values, return low.Peek(), which reads the top without removing it.
    8. Otherwise return the mean of the tops: (low.Peek() + high.Peek()) / 2.0.

    The solution in C#

    class MedianFinder {
        PriorityQueue<int, int> low = new PriorityQueue<int, int>(Comparer<int>.Create((x, y) => y - x));
        PriorityQueue<int, int> high = new PriorityQueue<int, int>();
        public void AddNum(int num) {
            low.Enqueue(num, num);
            int largest = low.Dequeue();
            high.Enqueue(largest, largest);
            if (high.Count > low.Count) {
                int smallest = high.Dequeue();
                low.Enqueue(smallest, smallest);
            }
        }
        public double FindMedian() {
            if (low.Count > high.Count) {
                return low.Peek();
            }
            return (low.Peek() + high.Peek()) / 2.0;
        }
    }
    

    The C# details worth knowing:

    • PriorityQueue<TElement, TPriority> takes two type arguments. It lives in System.Collections.Generic and has existed since .NET 6. Enqueue(element, priority) adds an item, Dequeue() removes and returns the element with the smallest priority, and Peek() returns it without removing it. There is no built-in max-heap, which is why low reverses the order with a comparer.
    • The comparer decides what "smallest" means. Comparer<int>.Create((x, y) => y - x) returns a positive number when x is smaller than y, so the larger value is treated as having the smaller priority.
    • y - x can overflow. With the lesson's numbers, which stay within ±100,000, it never does. For arbitrary int values the subtraction wraps silently: 10 - (int.MinValue + 5) evaluates to -2147483643 instead of a large positive number, so a safer comparer is y.CompareTo(x).
    • The field initializers run when the object is created. Each MedianFinder gets its own two heaps, so no constructor is needed.
    • Integer division truncates. 3 / 2 is 1 in C#, but 3 / 2.0 is 1.5, because one operand is a double. The sum of the two tops is an int, and dividing by 2.0 keeps the half.
    • The int return converts to double. return low.Peek(); in a method that returns double converts the int implicitly. An odd count therefore gives 2.0 rather than a whole number type.
    • Empty heaps throw. Peek() and Dequeue() throw InvalidOperationException when the heap is empty. This is why FindMedian relies on at least one number having been added.

    Complexity

    Time. AddNum does at most two Enqueue and two Dequeue calls, each O(log n), so it is O(log n). FindMedian only reads the top of one or two heaps, so it is O(1).

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

    Edge cases and common mistakes

    • A single number. After one AddNum(7), the number goes to low, moves to high, and moves back, because high would be bigger. FindMedian returns 7.0.
    • Even counts. After 4 and 3 the median is 3.5, the mean of the two tops.
    • Duplicates. Repeated values count each time. Adding 5, -3, -3 gives the median -3.0.
    • Negative numbers. They need no special handling: 5, -3 gives 1.0.
    • Asking twice. FindMedian only peeks, so calling it twice in a row returns the same value.
    • Dividing by 2 instead of 2.0. The code would return 1 for the tops 1 and 2, instead of 1.5.
    • Letting the halves drift apart. If high is allowed to grow larger than low, or the sizes differ by more than one, the tops are no longer the middle values.
    • Skipping the pass through low. Pushing a number straight into the half it seems to belong to needs a comparison against the tops. Always pushing into low and moving its largest value over makes that check unnecessary.

    Testing

    These call sequences were run, and FindMedian printed the values shown.

    • Add 1, 2, ask, add 3, ask gives 1.5 2.0.
    • Add 5, ask, add -3, ask, add -3, ask, add 10, ask gives 5.0 1.0 -3.0 1.0.
    • Add 4, 3, ask, ask, add 2, 1, ask gives 3.5 3.5 2.5.
    • Add 7, ask gives 7.0.
    • 20,000 random numbers between -100,000 and 100,000, checked against sorting the list every so often, give identical medians.
    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