TRT
Sign in
hardCoreLeetCode#two heaps

Find median from data stream

Maintain the median of a growing stream with a max-heap for the lower half and a min-heap for the upper half.

The Runtime Theory Team1 min read
Taught inTop-k and merging streamsPro — members onlyA heap of just k items finds the k largest of a billion in one pass. A heap of k stream heads merges k sorted streams. Two heaps keep a running median. These three patterns cover most heap problems.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inaddNum(1), addNum(2), findMedian(), addNum(3), findMedian()

out1.5, 2.0

inaddNum(-1), findMedian()

out-1.0

inaddNum(5), addNum(5), findMedian()

out5.0

Implement addNum(num) and findMedian() for a stream of integers.

Before you code

Keeping a sorted list makes each insert O(n). The median only depends on the two values in the middle, which are the largest of the lower half and the smallest of the upper half: the roots of two heaps.

Hints

  1. low is a max-heap (negate values in Python); high is a min-heap.
  2. Push into low, then move low's root to high, then if high is bigger, move its root back. That keeps the order and the sizes in one routine.
  3. The median is low's root if it has more elements, otherwise the average of both roots.

Production & complexity notes

When solving Find median from data stream on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Top-k and merging streams to reinforce the underlying pattern.

What it practices

Two heaps meeting in the middle, from Top-k and merging streams.

Not started

Sign in to save your learning progress.

Sign in to save