Two Heaps
O(log n) per op
A max-heap holds the lower half, a min-heap the upper half; keep their sizes balanced and the median sits on top.
Learn firstTop-K Elements
0%
mastery
0/5 solved
0/5 solved
Recognise it
The signal
Running median, sliding-window median, or two pools picked by different keys (IPO: affordable vs most profitable).
1Brute force
Sort after each insertion.
2The observation
Re-sorting: only the boundary between the halves matters.
3Why it works
Every element in the low max-heap <= every element in the high min-heap, and their sizes differ by at most one.
Reach for it when
- +sliding window median
- +two pools selected by different keys (IPO: affordable vs profitable)
Not when
- ×Arbitrary deletions without lazy-delete bookkeepinguse Ordered multiset
- ×You need the k-th element for arbitrary k, not just the middleuse Order-statistic tree or BIT
Practice
0/5 solved
- Find Median from Data StreamFoundationFoundationAmazon, GoogleHard
- Sliding Window MedianTwists · Elements also leave.TwistsHard
- IPOBranches · Two heaps keyed differently (capital vs profit).BranchesCitadel, Goldman SachsHard
- Sliding Window MedianMastery checkMastery checkCSESMedium
- Sliding Window CostCSESMedium
Pitfalls
Classic bugs
- !Forgetting to rebalance after every insert: push to one side, move its top across, then fix sizes so they differ by <= 1.
- !Sliding-window median: heaps can't delete by value; keep lazy-delete counts and purge tops when they're stale.