← Back to Algorithms, page 4

algorithms-0061 · Hard senior

Find the median from a data stream: support adding numbers and returning the current median, both efficiently.

Keep two heaps: a max-heap of the smaller half and a min-heap of the larger half, with the max-heap holding the same count or one more. Adding pushes through the max-heap into the min-heap and rebalances: O(log n). The median is the top of the max-heap, or the average of both tops: O(1). A sorted list with insort is the O(n)-per-insert baseline.

Full answer

Problem

Design MedianFinder with add(x) and median(). For an odd count the median is the middle value; for an even count it is the mean of the two middle values.

Example: add 1 (median 1.0), add 2 (median 1.5), add 3 (median 2.0).

Constraints: up to 5 * 10^4 calls; values from -10^5 to 10^5; median is only called when at least one value exists (the code raises otherwise).

Brute force

Maintain a sorted list and insert with binary search (bisect.insort). Finding the position is O(log n), but shifting elements makes each insert O(n). Sorting on every median call is O(n log n).

Optimal approach

Two heaps:

  • low: max-heap (store negatives in Python) holding the smaller half.
  • high: min-heap holding the larger half.

add(x): push x into low, pop the largest of low and push it into high, then if high has more items than low, move the smallest of high back. median(): if low is larger, return its top; otherwise average the two tops.

Why it works

Two invariants hold after every add: every value in low is at most every value in high (because each new value passes through low and its maximum is moved across), and len(low) is len(high) or one more. Together they mean the top of low is the lower middle and the top of high is the upper middle of the sorted sequence.

Complexity

add: O(log n), a constant number of heap operations. median: O(1). Space O(n).

Code

python
import bisect
import heapq
import random


class MedianFinder:
    """Two heaps: max-heap `low` (stored negated) and min-heap `high`.
    Invariant: every value in low <= every value in high, and len(low) is len(high) or one more."""

    def __init__(self):
        self.low, self.high = [], []

    def add(self, x):                    # O(log n)
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))   # move the largest of low across
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):                    # O(1)
        if not self.low:
            raise ValueError("no values yet")
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2


class SortedListMedian:
    """Brute force reference: insert into a sorted list, O(n) per insert."""

    def __init__(self):
        self.a = []

    def add(self, x):
        bisect.insort(self.a, x)

    def median(self):
        n = len(self.a)
        return float(self.a[n // 2]) if n % 2 else (self.a[n // 2 - 1] + self.a[n // 2]) / 2


if __name__ == "__main__":
    m = MedianFinder()
    for x, want in ((1, 1.0), (2, 1.5), (3, 2.0)):
        m.add(x)
        assert m.median() == want
    try:
        MedianFinder().median()
        assert False
    except ValueError:
        pass
    rng = random.Random(61)
    for _ in range(200):
        a, b = MedianFinder(), SortedListMedian()
        for _ in range(rng.randint(1, 60)):
            x = rng.randint(-20, 20)
            a.add(x)
            b.add(x)
            assert a.median() == b.median()
    print("all tests passed")

Save as b61_median_stream.py and run python3 b61_median_stream.py. It prints all tests passed (Python 3.13.5).

Edge cases

Empty structure (raise or return None, as agreed). All values equal. Negative values with the negation trick. Even counts must return a float average.

Pattern

Two heaps that split a set at a rank. Variants: sliding-window median (add lazy deletion or use a balanced BST), IPO-style capital selection, and scheduling problems that need the best item on each side of a threshold. If values come from a small range, counting buckets make median queries O(range) with O(1) inserts.

python
import bisect
import heapq
import random


class MedianFinder:
    """Two heaps: max-heap `low` (stored negated) and min-heap `high`.
    Invariant: every value in low <= every value in high, and len(low) is len(high) or one more."""

    def __init__(self):
        self.low, self.high = [], []

    def add(self, x):                    # O(log n)
        heapq.heappush(self.low, -x)
        heapq.heappush(self.high, -heapq.heappop(self.low))   # move the largest of low across
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def median(self):                    # O(1)
        if not self.low:
            raise ValueError("no values yet")
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2


class SortedListMedian:
    """Brute force reference: insert into a sorted list, O(n) per insert."""

    def __init__(self):
        self.a = []

    def add(self, x):
        bisect.insort(self.a, x)

    def median(self):
        n = len(self.a)
        return float(self.a[n // 2]) if n % 2 else (self.a[n // 2 - 1] + self.a[n // 2]) / 2


if __name__ == "__main__":
    m = MedianFinder()
    for x, want in ((1, 1.0), (2, 1.5), (3, 2.0)):
        m.add(x)
        assert m.median() == want
    try:
        MedianFinder().median()
        assert False
    except ValueError:
        pass
    rng = random.Random(61)
    for _ in range(200):
        a, b = MedianFinder(), SortedListMedian()
        for _ in range(rng.randint(1, 60)):
            x = rng.randint(-20, 20)
            a.add(x)
            b.add(x)
            assert a.median() == b.median()
    print("all tests passed")

Two-heap design with the push-through trick; random streams are checked against a sorted-list implementation after every insert.

Complexity

Time: O(log n) add, O(1) median. Space: O(n). For a bounded value range, a count array gives O(1) add and O(range) median.

By level

Fresher: Explains the sorted-list approach and then the idea of splitting values into two halves. Can trace adds with two heaps on a small example.

Mid: Implements the two heaps with correct balancing and states both invariants. Discusses the sliding-window variant and the need for deletions.

Senior: Discusses approximate quantiles at scale (t-digest, GK sketches), percentile monitoring, and merging per-shard summaries. Compares exact two-heap memory cost with sketch error bounds.

Key points

  • Max-heap for the lower half, min-heap for the upper half
  • Push through low into high, then rebalance
  • Sizes differ by at most one
  • Median from the tops
  • O(log n) add, O(1) query

Common mistakes

  • Forgetting to negate values for the max-heap in Python
  • Letting the size difference grow beyond one
  • Pushing directly into one heap without restoring the ordering invariant
  • Integer division for the even-count average

Follow-ups

  • How would you support a sliding window median?
  • What changes if 99% of values are in [0, 100]?
  • How would you approximate the median over billions of values in a distributed system?

Tips

  • State both invariants explicitly
  • Walk through three adds
  • Mention the sorted-list baseline and why it is O(n)

Evaluation rubric

  • Correct two-heap design
  • Invariants stated and maintained
  • Correct even and odd median
  • Correct complexity