#295

Find Median from Data Stream

Hard Two heaps

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Design a structure that adds numbers from a stream and returns the median of all numbers so far at any time.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the median after every new number.

Why this works: a max-heap holds the smaller half and a min-heap the larger half; the median is at the tops.

Example: add 1, 2, 3

low {1}, high {} → 1low {1}, high {2} → 1.5low {2, 1}, high {3} → 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Adding to one heap based only on size and not passing through the other heap — the halves can end up out of order.

Solve on LeetCode ↗
Complexity
  • Time: O(log n) add, O(1) median.
  • Space: O(n).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon