Streaming Median with Two Heaps
Track both heap sizes and the values at their roots after each arrival.
Core Intuition & How It Works
Tracking the running median of a live number stream uses two balanced heaps: a max-heap for the smaller half and a min-heap for the larger half. Rebalancing keeps their sizes within 1, making median queries O(1) and inserts O(log n).
In the Byte Sized Algorithms interactive classroom, you can step forward and backward through this algorithm with your keyboard while watching the visual diagram, memory state, and highlighted pseudocode update together.
Time & Space Complexity
| Metric | Complexity |
|---|---|
| Time Complexity | O(log n) insert, O(1) median |
| Space Complexity | O(n) |
| Topic Chapter | Chapter 8: Heaps & Priority Queues |
| Difficulty Level | Intermediate |
Key Pattern to Recognize
Insert into the lower max-heap, move its top to the upper min-heap to preserve ordering, then rebalance sizes if upper grows larger.
Common Pitfalls & Edge Cases
Forgetting to average both heap tops when the total element count is even, or violating max(lower) <= min(upper).
Real-World & Technical Interview Applications
Real-time latency percentile monitoring (p50), financial tick analytics, and online outlier detection.