Two heaps
medium 22 minThe two heaps pattern keeps a max-heap for the smaller half of the values and a min-heap for the larger half.
Video lesson · Chapter 1 of 8
Live ferry gauge
Two heaps in 75 seconds
1:17Reel
How it works
Step through the idea, or press Play.
Route by value. A new value joins the smaller half (a max-heap) if it is no bigger than that half's top, otherwise the larger half (a min-heap)
Understand it
Start here
Where priority queues left off
You already know heaps
Push and pop in , peek in , and Python's
heapqis min-only, so a max-heap stores negated values. Recap in heap operations.You have seen the running median
Priority queues sketched it in one section. This page takes it apart: the invariants, each method, the proofs and three harder problems.
What is new here
Rebalancing proofs, sliding window medians with lazy deletion, any percentile, and IPO, where two heaps on different keys drive a greedy choice.
The problem: numbers arrive one at a time, and after any of them someone may ask for the median, the middle value. Sorting everything each time works but repeats almost all of the work. Two heaps keep the data split around the middle permanently, so each new value costs only a few heap steps.
The median of n sorted values
The idea
Split the values into two halves
Picture a deck of cards split into two piles. The left pile holds the smaller cards with the largest of them on top; the right pile holds the bigger cards with the smallest on top. With 1 to 10 dealt out, the left top is 5 and the right top is 6, so the median is without looking at any other card.
Two heaps facing each other
- 1Arrivex comes in from the stream
- 2Comparex against the top of low
- 3Join a halfpush into low or high
- 4Maybe crossone root moves if sizes drift
- 5Roots answermedian from the tops
Invariants
The two rules that make it work
Order invariant
Balance invariant
Median from the roots
Method 1
add: route by value, then rebalance
add(x)
import heapqclass MedianFinder: def __init__(self): self.low = [] # max-heap of the smaller half (stored negated) self.high = [] # min-heap of the larger half def add(self, x): if not self.low or x <= -self.low[0]: heapq.heappush(self.low, -x) else: heapq.heappush(self.high, x) self.rebalance() def rebalance(self): if len(self.low) > len(self.high) + 1: heapq.heappush(self.high, -heapq.heappop(self.low)) elif len(self.high) > len(self.low): heapq.heappush(self.low, -heapq.heappop(self.high)) def median(self): if len(self.low) > len(self.high): return -self.low[0] return (-self.low[0] + self.high[0]) / 2mf = MedianFinder()for x in [41, 35, 62, 4, 97, 108]: mf.add(x) print(x, "->", mf.median()) # 41, 38.0, 41, 38.0, 41, 51.5Trace of the stream 41, 35, 62, 4, 97, 108
| add | routed to | rebalance | low (as a heap) | high (as a heap) | median |
|---|---|---|---|---|---|
| 41 | low (empty) | none | [41] | [] | 41 |
| 35 | low, | 41 to high | [35] | [41] | 38.0 |
| 62 | high, | 41 to low | [41, 35] | [62] | 41 |
| 4 | low, | 41 to high | [35, 4] | [41, 62] | 38.0 |
| 97 | high, | 41 to low | [41, 4, 35] | [62, 97] | 41 |
| 108 | high, | none | [41, 4, 35] | [62, 97, 108] | 51.5 |
Method 2
rebalance: why one move is enough
The gap argument
if, never a while.Moving a root never breaks the order invariant either. The max of low is the largest small value, so placing it in high keeps it no bigger than anything else there; the same holds for the min of high moving down. Sorted input (1, 2, 3, 4, 5) sends every value to high and forces a move on every other add; reversed input sends every value to low. Either way the halves end up as low = {1, 2, 3}, high = {4, 5}.
Method 3
findMedian: read the two roots
findMedian()
low[0].The three cases
| sizes | median | example |
|---|---|---|
| average of both tops | [41, 4, 35] and [62, 97, 108]: | |
| top of low | [41, 4, 35] and [62, 97]: 41 | |
| top of high (only if your convention allows it) | never happens with the rebalance above |
Cost
O(log n) to add, O(1) to read
One add
A whole stream, versus re-sorting
Ways to answer a median after every value
| approach | add | median | notes |
|---|---|---|---|
| Sort after each add | simplest, quadratic overall | ||
bisect.insort into a list | shift | fine for small n, shifting dominates | |
| Quickselect per query | average | good when queries are rare | |
| Two heaps | the standard answer | ||
| Sorted container or order-statistic tree | also supports delete and any rank | ||
| Counting array, values in 0..100 | the classic bounded-range follow-up |
Pattern
Sliding window median with lazy deletion
Now report the median of every window of size , as in a fixed sliding window. Each slide adds one value and removes one. Adding is easy; removing is the hard part, because a heap can only remove its root cheaply. The fix is lazy deletion: record the leaving value in a gone counter, adjust a live-size counter, and actually pop it only when it reaches a root.
One slide of the window
import heapqdef window_medians(nums, k): low, high = [], [] # max-heap (negated), min-heap gone = {} # value -> copies waiting to be deleted live = [0, 0] # real sizes of low and high def prune(h, sign): # pop dead values sitting on top while h and gone.get(sign * h[0], 0): gone[sign * h[0]] -= 1 heapq.heappop(h) def balance(): if live[0] > live[1] + 1: heapq.heappush(high, -heapq.heappop(low)) live[0] -= 1; live[1] += 1 prune(low, -1) elif live[1] > live[0]: heapq.heappush(low, -heapq.heappop(high)) live[1] -= 1; live[0] += 1 prune(high, 1) out = [] for i, x in enumerate(nums): if not low or x <= -low[0]: heapq.heappush(low, -x); live[0] += 1 else: heapq.heappush(high, x); live[1] += 1 if i >= k: y = nums[i - k] gone[y] = gone.get(y, 0) + 1 if y <= -low[0]: live[0] -= 1 prune(low, -1) else: live[1] -= 1 prune(high, 1) balance() if i >= k - 1: out.append(-low[0] if k % 2 else (-low[0] + high[0]) / 2) return outprint(window_medians([1, 3, -1, -3, 5, 3, 6, 7], 3)) # [1, -1, -1, 3, 5, 6]Pattern
IPO: maximize capital
You start with capital and may finish at most projects. Project needs capital to start and adds profit when done; capital is never spent, only gained. Two heaps on different keys solve it: locked, a min-heap by capital, releases projects as soon as you can afford them, and ready, a max-heap by profit, hands you the best one you can start now.
The two-heaps greedy
Why the greedy choice is safe
import heapqdef max_capital(k, w, profits, capital): locked = list(zip(capital, profits)) # min-heap by capital heapq.heapify(locked) ready = [] # max-heap by profit (negated) for _ in range(k): while locked and locked[0][0] <= w: c, p = heapq.heappop(locked) heapq.heappush(ready, -p) if not ready: break # nothing affordable: stop early w += -heapq.heappop(ready) return wprint(max_capital(3, 0, [1, 2, 3, 5], [0, 1, 1, 4])) # 9print(max_capital(2, 0, [1, 2, 3], [0, 1, 1])) # 4Generalise
Beyond the median: any percentile
The median is only the 50th percentile. To track the -th percentile of a stream, keep the same two heaps but change the target size of low: instead of half the values it holds the smallest of them, and the answer is its root. The old intuition that two heaps only do medians is too narrow; any fixed percentile works.
Target size for the p-th percentile (nearest rank)
Decide
When to reach for two heaps
Choosing a tool for middle values
Perfect for
- Median of a data stream
- Sliding window median (with lazy deletion)
- A fixed percentile of a stream, such as p90
- IPO-style greedy: unlock by one key, choose by another
- Scheduling with free and busy pools, such as meeting rooms III
Not ideal for
- Needing all values in sorted order
- Arbitrary rank queries that change every call (use an order-statistic tree)
- Very tight memory on huge streams (use an approximate sketch)
- Frequent deletions of arbitrary values outside a window
Classic problems
| problem | level | key insight |
|---|---|---|
| 295. Find Median from Data Stream | Hard | the core pattern: route, rebalance, read roots |
| 480. Sliding Window Median | Hard | two heaps plus lazy deletion and live counters |
| 502. IPO | Hard | min-heap by capital, max-heap by profit |
| 436. Find Right Interval | Medium | heaps by end and by start, popped in step (binary search also works) |
| 2402. Meeting Rooms III | Hard | free rooms by number, busy rooms by end time |
Recap
Key takeaways
Key points
- low is a max-heap of the smaller half, high is a min-heap of the larger half.
- Order: . Balance: low has the same size as high or one more.
- add routes by comparing with the top of low, then moves at most one root: .
- The median is the top of low, or the average of both tops: . Use
/ 2, not// 2. - Over a stream, two heaps cost in total; re-sorting each time costs .
- Sliding window median: mark leaving values as gone, prune only at the roots, balance on live counts.
- IPO: a min-heap by capital unlocks projects, a max-heap by profit picks the best; greedy is safe because capital only grows.
- Any fixed percentile works by making low hold values.