Skip to content

Find Median from Data Stream

Track a running median with two heaps: a max-heap for the low half and a min-heap for the high half.

HardHeaps and Top K
Solve on LeetCode

The problem

Design a class MedianFinder that receives integers one at a time and can report the median of all the numbers added so far. addNum(num) adds a number, and findMedian() returns the median: the middle value when the count is odd, or the average of the two middle values when it is even. You can assume findMedian is only called after at least one number has been added.

Input MedianFinder(), addNum(5), findMedian(), addNum(9), findMedian(), addNum(1), findMedian()

Output [null, null, 5.0, null, 7.0, null, 5.0]

After 5 and 9 the median is (5 + 9) / 2 = 7.0; after adding 1, the middle of 1, 5, 9 is 5.

Input MedianFinder(), addNum(-4), addNum(-4), addNum(10), addNum(2), findMedian()

Output [null, null, null, null, null, -1.0]

Sorted, the four numbers are -4, -4, 2, 10, so the median is (-4 + 2) / 2 = -1.0.

Key constraint: Up to 50,000 calls in total, so sorting all the numbers on every findMedian call is too slow.

How to spot the pattern

  • Numbers arrive one at a time and you need the middle of everything so far.
  • Only the boundary between the smaller half and the larger half matters.

The idea

Split the numbers into a lower half and an upper half. Keep the lower half in a max-heap and the upper half in a min-heap, so the two candidates for the middle sit on top of the two heaps. After every insert, rebalance so the lower half holds as many numbers as the upper half, or one more; then the median is the top of the lower heap, or the average of both tops when the sizes are equal.

Brute force: Keep all the numbers in a list and sort it on every findMedian call, which costs O(n log n) per call.

Step by step

  1. 1Keep a max-heap low for the smaller half and a min-heap high for the larger half.
  2. 2addNum: push the number into low, then move the largest value of low into high, so every value in low stays at most every value in high.
  3. 3If high now holds more values than low, move the smallest value of high back into low.
  4. 4findMedian: if low holds more values, return its top; otherwise return the average of the two tops.

See the pattern move

The heaps and top k pattern on a small example. Step through it, or press play.

Code

import heapq


class MedianFinder:

    def __init__(self):
        self.low = []   # smaller half as a max-heap (values are negated)
        self.high = []  # larger half as a min-heap

    def addNum(self, num: int) -> None:
        # Pass the number through low, so everything in low stays <= everything in high.
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        # Keep low the same size as high, or one larger.
        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 float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2

Complexity

Time

O(log n)

Space

O(n)

addNum does a constant number of heap pushes and pops; findMedian only reads the two tops, which is O(1).

Watch out for

  • Pushing a new number straight into one heap without passing it through the other, which can leave a value in low that is larger than a value in high.
  • Integer division when averaging the two middle values: (7 + 8) / 2 must be 7.5, not 7.
  • Forgetting that Python's heapq is only a min-heap: store negated values for the max-heap and negate them back when you read them.

Follow-up questions

If every number is between 0 and 100, how would you speed it up?

Keep a count for each of the 101 possible values. addNum becomes O(1), and findMedian walks the counts to the middle position, which is at most 101 steps.

What if you need the median of only the last k numbers?

Now old numbers must leave as well. Use the same two heaps with lazy deletion (remember values to remove and drop them when they reach a top), or a balanced tree or sorted list that supports removal. That is Sliding Window Median.

In Hinglish

Chhote half ko max-heap mein aur bade half ko min-heap mein rakho, dono ka size barabar ya low mein ek zyada. Median hamesha dono heaps ke top par hi milega.

Related problems