Start learning free

LESSON 177 OF 314 · HEAP

Find Median from Data Stream in Python: Two Heaps with heapq

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

    PYTHON · HEAP

    Find Median From Data Stream in Python, explained

    Problem overview

    The median of a list is its middle value once sorted. With an even number of values it 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 class MedianFinder receives numbers one at a time. addNum(num) adds an integer, and findMedian() returns the median of everything added so far. Duplicates count each time they arrive, and asking twice in a row gives the same answer because findMedian changes nothing. It is only called after at least one number has been added, and up to 500,000 calls are made in total.

    For example, after adding 1 and 2 the median is 1.5. After adding 3 the sorted numbers are [1, 2, 3] and the median is 2.

    Approach: keep the two halves in two heaps

    The simple approach keeps a list and sorts it whenever the median is requested. That costs O(n log n) per question, which is too slow for this many calls. Inserting each new number into a sorted list in the right place avoids the sort, but shifting elements still costs O(n) per number.

    The median depends only on the middle one or two values, so the rest of the order doesn't matter. Split the numbers into a lower half and an upper half, where every value in the upper half is at least every value in the lower half. The middle values are then the largest of the lower half and the smallest of the upper half. A heap gives access to exactly those: a max-heap for the lower half, whose top is its largest value, and a min-heap for the upper half, whose top is its smallest.

    The sizes are kept equal, or with the lower half one larger. Then:

    • if the lower half is larger, the count is odd, and the median is the top of the lower half;
    • if both halves have the same size, the median is the mean of the two tops.

    Pushing and popping a heap costs O(log n), and reading its top costs O(1), which matches the lesson's budget: addNum in O(log n) and findMedian in O(1).

    The heapq module only provides min-heaps, with the smallest value at index 0. To get a max-heap, store the numbers negated: the largest number becomes the smallest stored value. So self.low holds negated values, and self.high holds values as they are.

    Here is the state after each addNum for the numbers 4, 3, 2, 1 (the lists are shown sorted, and low is shown with the real values, not the negated ones):

    add 4  low [4]     high []      median 4
    add 3  low [3]     high [4]     median 3.5
    add 2  low [2, 3]  high [4]     median 3
    add 1  low [1, 2]  high [3, 4]  median 2.5
    

    Step by step

    1. Create self.low as an empty list in __init__. It is the max-heap of the lower half, storing negated numbers.
    2. Create self.high as an empty list. It is the min-heap of the upper half, storing numbers as they are.
    3. In addNum, push -num into self.low with heapq.heappush. Every new number enters the lower half first.
    4. Move the largest value of self.low into self.high. Popping the lower heap returns its smallest stored value, which is the negated largest real value. Negate it back and push it into the upper heap. Whatever num was, the value that leaves the lower half is its largest, so every value in the upper half stays at least every value in the lower half.
    5. Rebalance. If self.high now has more values than self.low, pop its smallest value and push it, negated, into self.low. After this, the halves have equal sizes, or self.low has one more.
    6. In findMedian, handle the odd count. If self.low has more values, return -self.low[0]: the top, negated back.
    7. Otherwise return the mean of the two tops: (-self.low[0] + self.high[0]) / 2.

    The solution in Python

    class MedianFinder:
        def __init__(self):
            self.low = []
            self.high = []
    
        def addNum(self, num: int) -> None:
            heapq.heappush(self.low, -num)
            heapq.heappush(self.high, -heapq.heappop(self.low))
            if len(self.high) > len(self.low):
                heapq.heappush(self.low, -heapq.heappop(self.high))
    
        def findMedian(self) -> float:
            if len(self.low) > len(self.high):
                return -self.low[0]
            return (-self.low[0] + self.high[0]) / 2
    

    Python details worth a closer look:

    • Heaps are plain lists. heapq works on an ordinary list and keeps the smallest element at index 0. Only that element is guaranteed in place: printing the list shows an arrangement that is not fully sorted. That is why the code reads self.low[0] and never the rest.
    • The negation trick. For the values -5, -9 and -1 pushed onto a heap, the top at index 0 is -9, the smallest. Storing -num turns "smallest stored" into "largest real", and every read or pop needs a negation to get back to the real value.
    • Integer or float. / always gives a float in Python 3, but the odd-count branch returns -self.low[0], which is an int. After adding only the number 7, findMedian() returns the integer 7. It equals 7.0 in a comparison, so it is a valid median.
    • Methods and self. The heaps are attributes created in __init__, so each MedianFinder has its own. Creating the lists at class level instead would share them between objects.

    Complexity

    Time: addNum is O(log n). It does at most two pushes and two pops, and each heap operation costs O(log n). findMedian is O(1): it reads one or two tops and does a bit of arithmetic.

    Space: O(n). Together the two heaps hold every number added.

    Edge cases and common mistakes

    • One number. After addNum(7), self.low holds it and self.high is empty. The odd branch returns it without touching self.high[0], which would raise IndexError on an empty list.
    • Duplicates. Adding 5, -3, -3 gives [-3, -3, 5] and the median is -3: the repeated number counts twice.
    • Negative numbers. The values are negated for storage, so a negative num is stored as a positive one. The code handles that without any special case.
    • Forgetting to negate on the way out. Returning self.low[0] instead of -self.low[0] gives the sign-flipped median.
    • Pushing straight into one heap. Sending each number to a heap by comparing it with the tops works, but needs more cases. Sending every number through the lower half and then moving its largest value across keeps the order between the halves automatically.
    • Letting the halves drift apart. If the sizes differ by more than one, or the upper half is larger, the tops are no longer the middle values. The rebalancing step prevents it.
    • Sorting on every query. Calling sorted in findMedian gives right answers but costs O(n log n) per call, which is too slow at this scale.

    Testing

    • Adding 1, 2, 3 and asking after each: 1, 1.5, 2.
    • Adding 5, -3, -3, 10: 5, 1.0, -3, 1.0.
    • Adding 4, 3, 2, 1: 4, 3.5, 3, 2.5.
    • Adding only 7: findMedian() returns 7.
    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free