Lesson 47 of 86IntermediatePro Interactive Lesson

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

MetricComplexity
Time ComplexityO(log n) insert, O(1) median
Space ComplexityO(n)
Topic ChapterChapter 8: Heaps & Priority Queues
Difficulty LevelIntermediate

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.

Unlock the full course

All 86 lessons across 15 chapters

View pricing

Delete account

This permanently deletes your account and ends any Pro access.