Four hard problems that cut a stream at a rank, or feed one heap from another. The move: state the cut, then restore order and balance after every change.
You work on an app that tracks response times, road estimates, viewer counts and loans. In each case the answer sits at a cut in a changing set: the middle of the values, or the point where what you can afford ends.
Two heaps hold the two sides of the cut, so that the values on either side of it are one step away. Here is what each problem adds to that picture.
| Problem | What the two heaps hold | What changes |
|---|---|---|
| Median of a stream of latencies | the lower half and the upper half | an even count averages the two middles, rounded down |
| Median of a data stream with two heaps | the lower and upper halves of the latest estimates | a new estimate replaces an old one of the same segment |
| Maximise capital before the deadline | loans waiting, and loans ready, by profit | the balance grows, so loans become ready |
| Sliding window median | the lower and upper halves of one window | the oldest value leaves as a new one enters |
The third row looks different, and it is. The two heaps there are not halves of one set. They share the idea that one heap feeds the other.
Exercise · Predict the output: The median of the latest estimates. Each event gives a new estimate for a road segment, and it replaces the older estimate of that segment. After each event the code prints the lower median of the latest estimates. What does it print?
latest = {}
for segment, seconds in [[1, 50], [2, 10], [1, 20], [3, 30], [2, 40]]:
latest[segment] = seconds
values = sorted(latest.values())
print(values[(len(values) + 1) // 2 - 1], end=" ")Before you write code, say where the cut is. For a median it is the middle, with the lower half on one side and the upper half on the other. Then write the two facts you must restore after every change.
Every value in the lower half is at most every value in the upper half. The lower half holds as many live values as the upper half, or one more. Restore both after every add and every removal.
The standard step has three parts. Put the new value in the lower half, and move the largest value of the lower half to the upper half. Then move one value back if the upper half has become larger. Both facts hold again, whichever half the new value belonged to.
The cost is the reason to do it. A window of 50,000 values moving over 100,000 values has 50,001 positions. Sorting every window touches 2,500,050,000 values, and the two heaps do a few operations per step.
Add to the lower half, move its top across, and move one back if the upper half is larger.
Exercise · Find the bug: Only one loan becomes ready. A lender starts with a balance and takes at most `rounds` loans. A loan can be taken when the balance reaches its minimum, and the best choice is the largest profit. Which line is wrong?
import heapq
def best_final_balance(profits, minimums, rounds, start):
order = sorted(range(len(profits)), key=lambda i: minimums[i])
ready = []
balance = start
next_loan = 0
for _ in range(rounds):
if next_loan < len(order) and minimums[order[next_loan]] <= balance:
heapq.heappush(ready, -profits[order[next_loan]])
next_loan += 1
if not ready:
break
balance -= heapq.heappop(ready)
return balanceThe Academy lesson Two heaps and running medians builds the median tracker and shows how to remove a value. Heaps and priority queues gives the heap itself, and Greedy with a heap takes the best choice that is ready. This street changes three things.
The median has a rule for an even count. The latencies 5, 2, 8, 1, 9 and 3 give the medians 5, 3, 5, 3, 5 and 4. With an even number of values the answer is the average of the two middles, rounded down, so the code reads both tops.
A value is replaced, not only added. When a segment sends a new estimate, its old value must leave the set. You cannot search a heap for it, so mark it as deleted in the half that holds it and reduce that half's live count.
Compare it with the value on top of the lower half to find the half. The marked value is thrown away when it reaches a top. For the events in the prediction, ignoring the replacement gives 50 10 20 20 30 instead of 50 10 10 20 30.
The two heaps can be two roles. In the loans problem, the lender can take loans in at most 2 rounds. With the minimums 0, 1 and 2, and profits 1, 2 and 3, a balance of 0 first affords one loan.
Taking it raises the balance to 1, which makes the second loan ready, so the best final balance is 3. The loans wait sorted by minimum, and a heap of profits holds the ready ones.
For the sliding window, a value leaves each time the window moves. With the viewer counts 5, 2, 8, 1, 9, 3 and 7, a window of 3 gives the medians 5, 2, 8, 3 and 7. A window of 4 gives 3, 5, 5 and 5, and the average of the two middles is rounded down.
An old value that stays in the set gives the wrong median. Mark it as deleted in the half that holds it.
Exercise · Break it: Order is not balance. This keeps a running median with two heaps. It always puts the new value in the lower half, and moves a value across only when the lower half is too large. Find an input where it gives a wrong answer.
import heapq
def running_medians(values):
lower = []
upper = []
answers = []
for v in values:
heapq.heappush(lower, -v)
if len(lower) > len(upper) + 1:
heapq.heappush(upper, -heapq.heappop(lower))
if len(lower) > len(upper):
answers.append(-lower[0])
else:
answers.append((-lower[0] + upper[0]) // 2)
return answersSolve them in this order. The first is the plain running median. The second adds a replaced value, the third changes what the heaps hold, and the fourth removes values as a window moves.
Before you code each problem, write three lines: where the cut is, what each heap holds, and what must be restored after a change. For the loans problem, the second line is the answer.
Give each problem about 35 minutes. Spend the first five on the three lines, and say them out loud as you would to an interviewer. Then list the edge cases.
Four cases come back on every rung: one value, two equal values, values that only increase, and a removal of the value on top of a half. Write one small test for each.
When a solution fails, print the sizes of both halves and their tops after every step. Most wrong answers on this street break the order of the halves or the balance of their sizes.
Checkpoint · Two heaps and medians
Q1/5 Which two facts must hold after every change in a two-heap median?
Answer: B
The first fact makes the two tops the middle of the set. The second makes the middle sit on the lower top for an odd count, or between the two tops for an even count.
Q2/5 The new value is larger than every value in the lower half. Why does the standard step still add it to the lower half first?
Answer: B
The value is added, and then the largest value of the lower half moves to the upper half. If the value was the largest, it moves across straight away. The order holds either way.
Q3/5 A segment sends a new estimate. What must happen to its old estimate?
Answer: B
A heap cannot search for a value cheaply. Marking it, and discarding it when it reaches a top, keeps every operation at O(log n) in total.
Q4/5 In the loans problem, why does a while loop, not an if, move loans into the heap of profits?
Answer: B
One loan taken can lift the balance past several minimums. All of them must be in the heap before the largest profit is chosen.
Q5/5 The values 4 and 7 are in a window, and the median of an even count is the average of the two middles, rounded down. What is it?
Answer: B
The average of 4 and 7 is 5.5, and rounding down gives 5.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.