Learn the pattern · ~15 min
Two Heaps
also called median maintenance, balanced heaps
Keep the smaller half in a max-heap and the larger half in a min-heap, balanced; the median is always at the roots.
Reach for it when you read
- +The median (or the k-th value) after every insert into a growing stream.
- +You only ever need the one or two values where a sorted list would split in half.
- +A window or stream where a value at a fixed rank must be read in O(1) after each change.
- +"Cost to move everything to one value": the median, plus the sum of each half.
Not this one when
- ×The k largest overall, read once at the end: one heap of size k.
- ×The median of two sorted arrays in O(log(m + n)): binary search on the partition.
- ×Tasks unlocked by time or capital (IPO, CPU scheduling): one heap of waiting items, not two halves.
Learn Two Heaps
First, what is a heap?
A heap is a box of numbers where you only see one of them: the top. In a max-heap the top is the biggest, in a min-heap the smallest. Push 4, 9 and 2 into a max-heap: the top is 9. Pop it: the top is 4.
Reading the top is O(1); a push or a pop is O(log n). Inside, the numbers aren't sorted. In C++, priority_queue<int> is a max-heap, and priority_queue<int, vector<int>, greater<int>> is a min-heap.
Two heaps use one of each to cut a list of numbers into a smaller half and a larger half. Sorted, 5, 15, 1, 3, 8, 7 is 1, 3, 5 | 7, 8, 15. The smaller half goes into a max-heap (top 5, the biggest of the small ones), the larger half into a min-heap (top 7, the smallest of the big ones). The two tops sit right at the cut.
How do we keep the halves while numbers keep coming?
Numbers arrive one at a time. Call the max-heap low and the min-heap high. Two rules must hold after every number:
- Every value in
lowis ≤ every value inhigh. lowhas the same size ashigh, or one more.
To add a number x, three moves:
Push x into
low. Movelow's top over tohigh. Ifhighis now bigger thanlow, movehigh's top back.
On 5, 15, 1, 3, 8, 7, heaps listed top first:
| add | what happens | low | high |
|---|---|---|---|
| 5 | in, across, and high is now bigger, so 5 comes back | 5 | |
| 15 | 15 goes in and crosses; sizes 1 and 1, fine | 5 | 15 |
| 1 | 1 goes in, the 5 crosses; high has 2, low 1, so 5 comes back | 5, 1 | 15 |
| 3 | 3 goes in, the 5 crosses; sizes 2 and 2, fine | 3, 1 | 5, 15 |
| 8 | 8 goes in and crosses straight out; high has 3, so its smallest, 5, comes back | 5, 3, 1 | 8, 15 |
| 7 | 7 goes in and crosses; sizes 3 and 3, fine | 5, 3, 1 | 7, 8, 15 |
After every row, the last two columns are the sorted list cut in half. Watch the 5: when 3 arrives it moves to high; when 8 arrives it comes back.
The code for it
priority_queue<int> low; // smaller half, biggest on top
priority_queue<int, vector<int>, greater<int>> high; // larger half, smallest on top
void add(int x) {
low.push(x); // 1. x goes into low
high.push(low.top()); low.pop(); // 2. low's biggest crosses to high
if (high.size() > low.size()) { // 3. high got too big?
low.push(high.top()); high.pop(); // its smallest comes back
}
}You don't need to memorise this. It's the three moves from the table: in, across, and back if high got too big.
Why push into low and move its top across, instead of checking which half x belongs to? Because then you never decide. What crosses is the biggest in low, x included, so what stays is ≤ it. And what stays is ≤ the old high too: if x crossed, low is as it was; if not, x was ≤ low's old top, which was ≤ all of high. So rule 1 holds, and the last line only fixes the sizes.
Fine, but how does this help us?
The classic problem: the median of a stream. After each number, report the median so far: the middle value, or with an even count, the average of the two middle ones.
For 5, 15, 1, 3, 8, 7, by hand:
| after | sorted so far | how you find the median | median |
|---|---|---|---|
| 5 | 5 | one number | 5 |
| 15 | 5, 15 | average of 5 and 15 | 10 |
| 1 | 1, 5, 15 | the middle one | 5 |
| 3 | 1, 3, 5, 15 | average of 3 and 5 | 4 |
| 8 | 1, 3, 5, 8, 15 | the middle one | 5 |
| 7 | 1, 3, 5, 7, 8, 15 | average of 5 and 7 | 6 |
So the answers are 5, 10, 5, 4, 5, 6.
The brute force
Keep a sorted array, insert each number where it belongs, read the middle.
void add(int x) {
sorted.insert(upper_bound(sorted.begin(), sorted.end(), x), x); // shifts everything after it
}
double median() {
int n = sorted.size();
if (n % 2) return sorted[n / 2];
return (sorted[n / 2 - 1] + (double)sorted[n / 2]) / 2;
}Finding the place is a binary search, but the insert shifts everything after it one step right. If the numbers arrive in falling order, each one goes to the front and shifts the whole array: about n²/2 moves, O(n²). For n = 10⁵ that's 5 × 10⁹ moves, but they run as fast block copies: we measured 0.3 seconds, so at LeetCode's limits it passes. At 10⁶ random numbers it took 15 seconds. Time limit exceeded.
The one thought that fixes it
Stop after the fourth number, the 3. The sorted list is 1, 3, 5, 15, and the median is the average of 3 and 5.
Now a fifth number x arrives. Where is the new middle?
- If x ≤ 3, x lands on the left. The middle is 3.
- If x ≥ 5, x lands on the right. The middle is 5.
- If x is between them, x itself is the middle.
The 1 and the 15 never mattered. The median needs only the biggest value of the left half and the smallest value of the right half.
Those are the two tops, and rule 2 keeps the halves balanced:
- odd count:
lowholds the extra number, so the median islow's top; - even count: the average of both tops.
add stays as it was. Only median() is new:
double median() {
if (low.size() > high.size()) return low.top(); // odd count: the middle is low's top
return (low.top() + (double)high.top()) / 2; // even: average of the two tops
}Dry run
| add | low (top first) | high (top first) | sizes | median |
|---|---|---|---|---|
| 5 | 5 | 1, 0 | low's top: 5 | |
| 15 | 5 | 15 | 1, 1 | (5 + 15) / 2 = 10 |
| 1 | 5, 1 | 15 | 2, 1 | low's top: 5 |
| 3 | 3, 1 | 5, 15 | 2, 2 | (3 + 5) / 2 = 4 |
| 8 | 5, 3, 1 | 8, 15 | 3, 2 | low's top: 5 |
| 7 | 5, 3, 1 | 7, 8, 15 | 3, 3 | (5 + 7) / 2 = 6 |
5, 10, 5, 4, 5, 6, the same answers as the brute force.
Why it's O(log n)
One add does a push, a pop and a push to cross, and at most a pop and a push to rebalance: at most five heap operations, each O(log n). The same 10⁶ numbers took 0.13 seconds. median() only reads two tops: O(1). The heaps hold every number once, so space is O(n).
From O(n) per number to O(log n), by keeping only the two values at the cut in sight.
Numbers that also leave? Sliding window median
Now the median of every window of k numbers. A number must also leave, but a heap can only remove its top. So delete lazily: count the leaving number as "to delete" and pop it for real only when it reaches a top. Rule 2 then counts only live numbers.
del[out]++; // remove later, once it shows up on a topOn 5, 15, 1, 3, 8, 7 with k = 3 the window medians are 5, 3, 3, 7.
The cost to move everything to the median? Keep two sums
"Make every number equal, each ±1 costs 1": the best target is the median m. Keep sumLow and sumHigh beside the heaps, update them on every push and pop, and the cost is one line:
long long cost = m * ls - sumLow + sumHigh - m * hs; // low values rise to m, high values drop to mAfter all six numbers, m = 5, low sums to 9 and high to 30: 5·3 − 9 + 30 − 5·3 = 21. Check: 0 + 10 + 4 + 2 + 3 + 2 = 21.
Remember this
- Smaller half in a max-heap, larger half in a min-heap.
- Fix which heap holds the extra number;
median()depends on it. - Cast before averaging:
low.top() + high.top()can overflowint. - Equal values are fine: rule 1 says ≤, not <.
- Whenever a problem asks for "the median, or a value at a fixed rank, after every change", it's two heaps.
Practise it on Find Median from Data Stream, then Sliding Window Median (numbers leave, delete lazily), Sliding Median and Sliding Cost (the sums of each half), IPO (locked and unlocked) and Single-Threaded CPU (unlocked by a clock).
Below, watch Find Median from Data Stream run line by line.
Watch it work, line by line
Find Median from Data Stream ↗, stream = 5, 15, 1, 3, 8 → 5.0 10.0 5.0 4.0 5.0. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Do I need the middle (or a fixed split point) of a set that keeps changing, or two pools of items where items move from one to the other?
Reach for it when
- +running median
- +sliding window median
- +two pools selected by different keys (IPO: affordable vs profitable)
- +n up to 1e5 inserts/queries
It fails 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
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Which heap holds which half, and which root is the median for an odd count?Reveal
The smaller half in a max-heap (
low), the larger half in a min-heap (high). Withlowkeeping the extra value, the odd median islow.top().2What two things must stay true after every insert?Reveal
Everything in
low≤ everything inhigh, andlow.size()ishigh.size()or one more.3Why does the sliding-window median need extra work?Reveal
Values leave the window, and a heap can't delete an arbitrary value. Mark them for lazy deletion and drop them when they reach a root, or use a multiset.
Practice ladder
Finished Two Heaps? Mark it done and Lessgo moves you to the next step.