Find Median from Data Stream

Find the median of a stream of numbers.

Pattern

Two Heaps

This problem follows the Two Heaps pattern, commonly found in the Heap / Priority Queue category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Max-heap for lower half, min-heap for upper half. Balance sizes after each insert.

Key Insight

The two heaps partition the data at the median — the max-heap root is the largest of the smaller half, the min-heap root is the smallest of the larger half.

Step-by-step

  1. 1Maintain a max-heap for the lower half and a min-heap for the upper half
  2. 2On each insert, add to the appropriate heap
  3. 3Balance the heaps so they differ in size by at most 1
  4. 4The median is the top of the larger heap (or average of both tops)

Pseudocode

lo = []  # max-heap (negated)
hi = []  # min-heap
def addNum(num):
    heappush(lo, -num)
    heappush(hi, -heappop(lo))
    if len(hi) > len(lo):
        heappush(lo, -heappop(hi))

def findMedian():
    if len(lo) > len(hi):
        return -lo[0]
    return (-lo[0] + hi[0]) / 2
Complexity Analysis

Time Complexity

O(log n)

Space Complexity

O(n)
More Heap / Priority Queue Problems

Master this pattern with YeetCode

Practice Find Median from Data Stream and similar Heap / Priority Queue problems with flashcards. Build pattern recognition through active recall.

Practice this problem