Keep a lower half and an upper half in two heaps to read the median or a percentile of a stream at any time.
An online exam portal shows the median score while students submit their papers. Scores arrive one at a time, and after each one the bar must show the middle score so far. The median is steady when a few students score very high or very low, which is why teachers like it.
Sorting every score after each new paper would be far too slow. You do not need the whole sorted list. You need only the middle one or two values.
Children line up for a photo in two rows. The front row holds the shorter half, and the back row holds the taller half. The tallest child of the front row and the shortest child of the back row stand at the cut, side by side.
A new child joins the row where they fit. If one row gets too long, the child standing at the cut steps across to the other row. The two children at the cut are always the middle of the whole group.
Two rows for a photo: the shorter half in front and the taller half behind. The two children at the cut are the middle of the group.
Split the values seen so far into a lower half and an upper half. Every value of the lower half is at most every value of the upper half. So the largest value of the lower half and the smallest value of the upper half are the two middle values.
A heap hands out its best item in one step, so use two. The lower half is a max-heap, with its largest value on top. The upper half is a min-heap, with its smallest value on top. The two tops sit on either side of the cut.
The first rule is the order: every lower value is at most every upper value. The second rule is the size: the lower half holds the same number of values as the upper half, or one more. With these two rules, the median is the lower top for an odd count, and the average of both tops for an even count.
Step by step: The upper half of a stream, in an array. The animated player loads in your browser.
Exercise · Put it in order: Climbing in the lower half. The lower half is a max-heap: every parent is no smaller than its children. Arrange the lines into a function that sifts the item at cell i up, and returns the array.
def sift_up_max(cells, i):
while i > 0:
parent = (i - 1) // 2
if cells[parent] >= cells[i]:
break
cells[parent], cells[i] = cells[i], cells[parent]
i = parent
return cells
if cells[parent] <= cells[i]:Predict what happens
Q Four scores have arrived. The lower half holds 3 and 5, and the upper half holds 8 and 12. Which two values are at the cut?
Answer: B
The lower half is a max-heap, so its top is its largest value, 5. The upper half is a min-heap, so its top is its smallest value, 8. They are the two middle values.
A new value goes to the lower half when it is at most the lower top, and to the upper half otherwise. If the lower half is empty, it goes there. That keeps the order rule.
The size rule may now be off by one. If the lower half has two values more than the upper half, pop its top and push it into the upper half. If the upper half has one value more than the lower half, pop its top and push it into the lower half. One move is always enough, because a single add changes a size by one.
Trace it on the scores 8, 3, 12, 5, 9, 1. The first score, 8, goes to the lower half. The score 3 is at most 8, so it joins the lower half too. The lower half now has two values and the upper half none, so the 8 moves up.
Then 12 goes to the upper half, because it is larger than the lower top, 3. The upper half has two values to one, so its top, 8, moves down to the lower half. After six scores the lower half holds 1, 3 and 5, and the upper half holds 8, 9 and 12.
Exercise · Predict the output: Where is the cut after seven values?. Each value goes into the lower half, which is a max-heap. Its top then moves to the upper half, a min-heap, and if the upper half is now bigger, its top moves back. After these seven values, what do the two tops print, lower first?
import heapq
lower, upper = [], []
for value in [10, 4, 6, 20, 1, 15, 3]:
heapq.heappush(lower, -value)
heapq.heappush(upper, -heapq.heappop(lower))
if len(upper) > len(lower):
heapq.heappush(lower, -heapq.heappop(upper))
print(-lower[0], upper[0])To add a value, compare it with the lower top and push it to that side. Then move one top across if a half is too big.
Step by step: Push 9 into the upper half, then move its top across. The animated player loads in your browser.
Exercise · Break it: The median that never rebalances. This function returns the median of a list of non-negative numbers: the middle one, or the average of the two middle ones rounded down. It puts each value in the right half, but it never moves a top across. Find a list where it gives the wrong answer. Use at least one value.
import heapq
def final_median(values):
lower, upper = [], []
for value in values:
if not lower or value <= -lower[0]:
heapq.heappush(lower, -value)
else:
heapq.heappush(upper, value)
if len(lower) > len(upper):
return -lower[0]
return (-lower[0] + upper[0]) // 2Predict what happens
Q The lower half holds 5 and 3, with 5 on top. The upper half holds 8 and 12. The score 9 arrives. What happens?
Answer: C
9 is larger than the lower top, 5, so it joins the upper half. The upper half then has three values to the lower half's two, so its top, 8, moves across. The halves now hold 3, 5, 8 and 9, 12.
For an odd count, the median is the lower top. For an even count, it is the average of the two tops. Reading it is a peek at one or two heap tops, so it costs O(1).
After the scores 8, 3, 12, 5, 9, 1, the medians are 8, 5, 8, 6, 8 and 6. The even counts average the two tops: for example 3 and 8 give 5, and 5 and 8 give 6, both rounded down.
The sum of two tops is where a 32-bit int breaks. Two latencies near 2 billion add up to more than the largest int, which is about 2.147 billion. Add them as 64-bit numbers, then halve.
The even median adds two tops. Two values of two billion add up to four billion, so add them as 64 bit numbers.
Exercise · Find the bug: The median that ignores the upper half. This keeps the median after every value. The sizes are balanced correctly, but the medians it reports are wrong whenever the count is even. Which line is wrong?
import heapq
def running_medians(values):
lower, upper = [], []
out = []
for value in values:
if not lower or value <= -lower[0]:
heapq.heappush(lower, -value)
else:
heapq.heappush(upper, value)
if len(lower) > len(upper) + 1:
heapq.heappush(upper, -heapq.heappop(lower))
elif len(upper) > len(lower):
heapq.heappush(lower, -heapq.heappop(upper))
if len(lower) >= len(upper):
out.append(-lower[0])
else:
out.append((-lower[0] + upper[0]) // 2)
return outPredict what happens
Q Five scores are in. The lower half holds 3, 5 and 8, and the upper half holds 9 and 12. What is the median?
Answer: B
With five values the lower half has one more than the upper half, so the median is its top, 8. You average the two tops only for an even count.
The median is the cut at one half. A percentile is the same cut at another place. For the 90th percentile of m values, the lower heap holds exactly the rank smallest values, where rank is (9m + 9) // 10.
For m from 1 to 12 the rank is 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 10 and 11. It rises with each value except once in a while, when it stays the same. So after each add, run two small loops.
While the lower heap is too big, move its top up. While it is too small, move the upper top down. The 90th percentile is the lower top.
A percentile is the same cut at a fixed rank. The lower heap holds exactly the rank smallest values, and two small loops keep it so.
Each heap can keep a running total next to its values. When a top moves across, subtract it from one total and add it to the other. Then the totals of the lower and upper halves are always ready, without re-adding anything.
The two heaps need not be two halves of the values. In a hiring queue, the left heap can hold the first c workers still waiting, and the right heap the last c. The cheapest candidate is the smaller of the two tops. When a worker is hired, the next unseen worker on that side joins its heap.
A heap has no index, so finding a value in the middle costs O(n) before it can be removed. A sliding window median needs this, because old values leave the window. The trick is lazy deletion.
Note the leaving value in a map of waiting deletions, and update the number of live values in its half. A value is removed for real only when it reaches the top of its heap. Until then, it stays in the heap but is not counted.
A heap cannot delete from the middle quickly. Note the leaving value in a map, and drop it only when it reaches the top.
Predict what happens
Q You want the 90th percentile after 11 values. The rank is (9 * 11 + 9) // 10. How many values must the lower heap hold?
Answer: C
The rank is (99 + 9) // 10 = 10. The lower heap holds exactly the 10 smallest values, and the upper heap holds the 1 largest.
Here is the pair of heaps next to two plainer ways to keep a running middle. The last two rows are where the difference is largest.
| Operation | Two heaps | Sorted list with binary search | Re-sort after every value |
|---|---|---|---|
| Push a value | O(log n): into one heap | O(n): later values shift along | O(n log n): sort again |
| Pop a top and move it across | O(log n): a pop and a push | Not needed | Not needed |
| Peek at the median (the two tops) | O(1) | O(1): read the middle cell | O(1) after the sort |
| Build both heaps from n values (heapify) | O(n) | O(n log n): a sort | O(n log n) |
| Search for a given value | O(n): a heap has no search order | O(log n) | O(log n) after the sort |
| Remove a value from the middle | O(log n) amortised, with lazy deletion | O(n): later values shift back | O(n log n) |
| Median after each of n values | O(n log n) | O(n^2) | O(n^2 log n) |
Two heaps win when values keep arriving and you read the middle after each one. A sorted list is better when you need lookups or the rank of any value.
Now drive a heap yourself. The upper half is a min-heap, so the default variant shows it. Switch the variant to max to see the lower half, which keeps its largest value on top.
Try these five, in order:
The sandbox: build a list and run its operations step by step. It loads in your browser.
Now write the tracker yourself. The lab gives you a MedianTracker class that keeps a lower half in a max-heap and an upper half in a min-heap. You write six methods: add, median, lower_top, upper_top, sizes and lower_total.
Four things to take care over:
(m + 1) // 2 of the m values, so the lower half has the same count as the upper half or one more.median returns the lower top for an odd count, and the average of both tops for an even count, rounded down. Return -1 when nothing has been added.int, so use a 64-bit sum for the average.lower_total is the total of the lower half. Update it whenever a value enters the lower half or a top moves across, and never add the whole heap again.When a test fails, the result names the exact call that went wrong, the value it returned and the value it should return.
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
Use two heaps when values keep arriving and you must read the median, a percentile or a total of each half after every value. Each add costs O(log n) and each read costs O(1).
It also fits any task where a cut moves slowly: the cheapest of the two ends of a list, or the median of a window with lazy deletion.
If you need the median once, at the end, sorting the list or a selection method is simpler. If you need the rank of any value, or the item at any position, choose a sorted structure or a search tree. Two heaps give only the two middle values, and nothing else.
A single heap gives the smallest or the largest, never the middle. The median needs both sides of the cut, one on top of each heap. Two heaps of the same kind cannot work, because the lower half needs its largest value on top.
heapq.heappush(lower, value) # a min-heap: the top is the smallest, not the cut
heapq.heappush(lower, -value) # a max-heap in disguise: the top is the largestAfter an add, the sizes are off by one at most, so a single move across restores them. Forgetting to rebalance lets one heap grow without limit, and then the tops are no longer the middle.
heapq.heappush(upper, value) # missing: if len(upper) > len(lower): move the top acrossSkipping the rebalance lets one heap grow. The lower top is then not the middle, and the median is wrong.
The even-count median adds two tops. Two values near 2 billion add up to about 4 billion, which wraps in a 32-bit int in Java and is undefined in C++. Add as 64-bit numbers, then halve and round down.
int median = (lower + upper) / 2; // overflows near 2 billion
long median = ((long) lower + upper) / 2; // correctWhen a max-heap is a min-heap of negated values, every read needs a minus sign. Reading lower[0] gives minus the largest value. Push -value, pop and negate, and read -lower[0].
median = lower[0] # wrong: this is minus the largest value
median = -lower[0] # rightA heap has no fast way to remove a value that is not on top. Scanning for it costs O(n) for each removal. Use lazy deletion instead: record the value, and drop it when it reaches the top.
lower.remove(old) # scans every cell, and the heap must then be rebuilt: O(n)Explain the idea in your own words, then take the checkpoint quiz.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The halves and the invariant
Q1/3 You keep the median of a stream with two heaps. Which kind of heap holds the lower half?
Answer: B
The cut sits between the largest lower value and the smallest upper value. So the lower half is a max-heap, and the upper half is a min-heap.
Q2/3 What is the size rule of the two-heap pattern?
Answer: C
With the lower half one larger for an odd count, the median is the lower top. For an even count both halves are equal, and the median is the average of the two tops.
Q3/3 The lower half holds 3, 5 and 8 (top 8). The upper half holds 9 and 12 (top 9). The score 1 arrives. Where does it go, and what moves?
Answer: C
1 is at most 8, so it joins the lower half. The lower half then holds 1, 3, 5 and 8 against two values above, which is two too many, so its top, 8, moves across.
Checkpoint · Reading the median
Q1/3 Five scores are in: the lower half holds 3, 5 and 8, and the upper half holds 9 and 12. What is the median?
Answer: B
The count is odd, so the lower half has one more value, and its top, 8, is the median.
Q2/3 After the scores 8, 3, 12 and 5 the lower half holds 3 and 5, and the upper half holds 8 and 12. What is the median, rounded down?
Answer: C
The count is even, so average the two tops: 5 and 8 give 6.5, and rounding down gives 6.
Q3/3 Two latencies of 2,000,000,000 each are the two tops. Which way of computing their average is safe in Java?
Answer: C
The sum, 4,000,000,000, is larger than the largest int. Cast one value to long before adding, then halve.
Checkpoint · Ranks, ends and removal
Q1/4 You want the 90th percentile after 10 values, with the rank (9 * m + 9) // 10. How many values does the lower heap hold?
Answer: D
The rank is (90 + 9) // 10 = 9. The lower heap holds the 9 smallest values, and the upper heap holds the largest one.
Q2/4 A hiring queue lets you hire the cheapest of the first c and the last c workers. What do the two heaps hold?
Answer: B
The two heaps hold the two ends of the list, not two halves of the sorted values. The cheapest candidate is the smaller of the two tops.
Q3/4 A window moves along a stream and a value leaves it. How does a heap-based window median remove that value?
Answer: B
A heap cannot delete from the middle quickly. Lazy deletion keeps the value in the heap, uncounted, until it reaches the top.
Q4/4 You need the median of a list once, at the end. What is the better choice?
Answer: B
Two heaps pay off when you need the middle after each of many values. For one answer, sorting is simpler and as fast.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Sandbox and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.