Skip to main content
TRACK B · ALGORITHMmedium•NOVEMBER 2026•6 MIN

Two Heaps: Live Streaming Median & Order Stats

Split a stream into a max-heap lower half and min-heap upper half to maintain the live median in O(log n) per insert and O(1) per query.

two heapsstreamingheapmedianorder-statistics

The core idea

A single heap only exposes one extreme (min or max). To track the middle of a growing stream without re-sorting, split elements into two balanced heaps: a max-heap lo for the smaller half and a min-heap hi for the larger half, preserving max(lo) ≤ min(hi) and 0 ≤ len(lo) - len(hi) ≤ 1.

Watch it run

Step through the trace below to watch every incoming number route through lo into hi and rebalance automatically.

LOADING TWO HEAPS MEDIAN SIM...

Key Takeaway

Canonical Python template

import heapq

class MedianFinder:
    def __init__(self) -> None:
        self.lo: list[int] = []  # max-heap via negated ints
        self.hi: list[int] = []  # min-heap

    def add_num(self, x: int) -> None:
        heapq.heappush(self.lo, -x)
        heapq.heappush(self.hi, -heapq.heappop(self.lo))
        if len(self.hi) > len(self.lo):
            heapq.heappush(self.lo, -heapq.heappop(self.hi))

    def find_median(self) -> float:
        if len(self.lo) > len(self.hi):
            return float(-self.lo[0])
        return (-self.lo[0] + self.hi[0]) / 2.0

Related Lab Entries