Find Median from Data Stream (LeetCode 295): Solution and Explanation

Hard
Two Pointers
Data Stream
Sorting
Heap
Design

Build a MedianFinder class that accepts integers one at a time through addNum and can report the median of everything seen so far through findMedian. With an odd count the median is the middle value, and with an even count it is the average of the two middle values.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The simplest design keeps every number in a list and sorts it whenever the median is requested, which is O(n log n) per query. Keeping the list sorted with insertion is better, since binary search finds the position in O(log n), but shifting elements to make room still costs O(n) per add. With many interleaved calls, both approaches get slow.

Notice that the median only depends on the boundary between the smaller half and the larger half of the data. You do not need the halves sorted internally; you just need fast access to the largest value of the lower half and the smallest value of the upper half. That is exactly what a max-heap and a min-heap provide.

So keep the lower half in a max-heap called small and the upper half in a min-heap called large. Two invariants make this work: every value in small is at most every value in large, and the two sizes differ by at most one. Each insert might break one of these, but fixing it takes at most a couple of heap moves. Then the median is the top of the bigger heap, or the average of both tops when the sizes are equal. Python only has a min-heap, so small stores negated values.

Approach: Two heaps split at the median

  1. Keep small as a max-heap (stored as negatives) for the lower half and large as a min-heap for the upper half.
  2. In addNum, push the new number onto small first.
  3. If the largest value in small is greater than the smallest value in large, pop it from small and push it onto large so the ordering invariant holds.
  4. If small has more than one extra element, move its top to large. If large has more than one extra element, move its top to small.
  5. In findMedian, return the top of whichever heap is larger. If the sizes are equal, return the average of both tops.

Step-by-step example

addNum(1), addNum(2), findMedian(), addNum(3), findMedian()
  1. Add 1: it goes into small. large is empty, so nothing moves. Now small holds {1}.
  2. Add 2: it goes into small, whose top is now 2. large is empty so the ordering check is skipped, but small has 2 elements against 0, so 2 moves to large.
  3. findMedian: the sizes are equal, so return (1 + 2) / 2 = 1.5.
  4. Add 3: it goes into small, making its top 3. Since 3 is greater than the top of large (2), move 3 to large, which now holds {2, 3}.
  5. The sizes are 1 and 2, a difference of one, so no rebalance is needed. findMedian returns the top of large, which is 2.

Code: Python, Java, C++

1class MedianFinder:
2    def __init__(self):
3        self.small, self.large = [], []
4
5    def addNum(self, num: int) -> None:
6        heapq.heappush(self.small, -1 * num)
7        
8        # Make sure every num small is <= every num in large
9        if self.small and self.large and (-1 * self.small[0]) > self.large[0]:
10            val = -1 * heapq.heappop(self.small)
11            heapq.heappush(self.large, val)
12            
13        # Uneven size?
14        if len(self.small) > len(self.large) + 1:
15            val = -1 * heapq.heappop(self.small)
16            heapq.heappush(self.large, val)
17        if len(self.large) > len(self.small) + 1:
18            val = heapq.heappop(self.large)
19            heapq.heappush(self.small, -1 * val)
20
21    def findMedian(self) -> float:
22        if len(self.small) > len(self.large):
23            return -1 * self.small[0]
24        if len(self.large) > len(self.small):
25            return self.large[0]
26        return (-1 * self.small[0] + self.large[0]) / 2

Time and space complexity

Time

O(log n) per addNum, O(1) per findMedian

Each insert does a constant number of heap pushes and pops, each costing O(log n). Reading the median only looks at heap tops.

Space

O(n)

Every number added is stored in exactly one of the two heaps.

Other approaches

Sorted list with binary insertion (time O(n) per add, O(1) per median, space O(n))

Keep a sorted array, use binary search to find each insert position, and read the middle element directly. Queries are O(1), but inserting shifts elements, so each add is O(n).

Counting buckets for a small value range (time O(1) per add, O(R) per median, space O(R))

If all numbers fall in a small fixed range such as 0 to 100, keep a count per value and scan the counts to locate the middle positions. Adds are O(1) and queries cost the size of the range.

Common mistakes

  • Forgetting to negate values when using Python's min-heap as a max-heap, both when pushing and when reading the top.
  • Rebalancing sizes without first fixing the ordering. A large number pushed into small must move to large even if the sizes look fine.
  • Using integer division for the even case. The median of 1 and 2 is 1.5, so divide as a float.
  • Letting the heaps drift more than one element apart, which makes the tops stop representing the middle.

Frequently asked questions

Why use two heaps to find a running median?

The median sits at the boundary between the lower and upper halves. A max-heap gives instant access to the top of the lower half and a min-heap to the bottom of the upper half, and both support O(log n) inserts.

What is the time complexity of the two-heap median finder?

Each addNum is O(log n) because of a constant number of heap operations, and each findMedian is O(1). Space is O(n) for storing all numbers.

How do you implement a max-heap in Python?

The heapq module only provides a min-heap, so push the negated value and negate again when you read or pop. The smallest negated value is the largest original value.

How would you handle a sliding window median instead?

You still use two halves, but you also need to remove values that leave the window. Lazy deletion with a hash map of pending removals, or a balanced sorted structure, handles that efficiently.