Let a heap hold the choices seen so far, and take or give back the best one when a limit is reached.
You work on the offers screen of a ride-hailing app. During an evening, ride offers arrive one by one, each with a fare in units. A driver's plan holds at most 3 rides, and a planned ride can be dropped when a better offer arrives. Your team lead says: "After every offer, show the three best fares so far, and their total."
Here are seven offers, in the order they arrive.
| Offer | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| Fare | 8 | 3 | 9 | 5 | 12 | 4 | 7 |
The first attempt is correct. After each offer, sort all the offers so far and read the three largest fares. For seven offers that is nothing.
Now check the real size. An evening can bring 100,000 offers. A sort of 100,000 fares costs about 100,000 × 17 steps. You sort again after every offer, so the sorts add up to about 8 × 10^10 steps.
We need to avoid sorting again and again.
You make a playlist for a trip, and it has room for 3 songs. You add each new favourite. When the list has 4 songs, you remove the one you like least. You never sort your whole music library again.
The playlist is the plan. The song you like least is the choice to give back, and you must find it fast. A min-heap puts the smallest item on top, so the song you like least is always the one you can see.
The picture is wrong in one way. A real playlist lets you remove any song. Here you only ever remove the smallest, and that is what makes the heap enough.
A trip playlist has room for three songs. When there are four, you remove the one you like least. A min-heap shows that song at once.
This is greedy with a heap. You keep the choices you have taken in a heap. When a limit is reached, you give back the worst one. The heap finds it in log n steps, so each new offer costs about log 3, which is 2 steps, not a full sort.
Run it on the seven offers. The heap holds fares, and the smallest is on top.
| Offer | Fare | Given back | Heap after (smallest first) | Total |
|---|---|---|---|---|
| 1 | 8 | none | 8 | 8 |
| 2 | 3 | none | 3, 8 | 11 |
| 3 | 9 | none | 3, 8, 9 | 20 |
| 4 | 5 | 3 | 5, 8, 9 | 22 |
| 5 | 12 | 5 | 8, 9, 12 | 29 |
| 6 | 4 | 4 | 8, 9, 12 | 29 |
| 7 | 7 | 7 | 8, 9, 12 | 29 |
Keep a min-heap of three fares. Push each new fare, and when the heap holds four, pop the smallest.
After offer 6 the fare 4 is smaller than everything in the heap, so it is pushed in and given back at once. The heap always holds the three largest fares seen so far, and it is right after every offer.
Exercise · Predict the output: Which fares does the plan give back?. The plan holds the 3 best fares, kept in a min-heap, and gives back the smallest whenever a fourth arrives. Seven offers arrive in this order. The program prints each fare given back, in order. What does it print?
import heapq
fares = [6, 2, 9, 4, 7, 1, 8]
plan = []
back = []
for fare in fares:
heapq.heappush(plan, fare)
if len(plan) > 3:
back.append(heapq.heappop(plan))
print(*back)Predict what happens
Q The heap holds the fares 3, 8 and 9, and a new offer of 5 arrives. What happens?
Answer: B
The plan holds 3 rides. The new fare 5 beats the smallest fare, 3, so 3 is pushed out. The heap then holds 5, 8 and 9, and the total is 22.
Exercise · Break it: Find the offers where the plan keeps a weak fare. This plan holds up to 3 fares. A new fare replaces the most recently added one when it is bigger, and the function returns the total of the plan. Find a list of fares where the total is lower than the best three fares add up to.
def best_three_total(fares):
plan = []
for fare in fares:
if len(plan) < 3:
plan.append(fare)
elif fare > plan[-1]:
plan[-1] = fare
return sum(plan)The count limit was easy. Now a limit that depends on time. A parcel-delivery app has one courier, and each parcel takes some hours and has a deadline hour.
The courier starts at hour 0 and does one parcel at a time with no gaps. A parcel that finishes exactly at its deadline is on time.
Your team lead says: "Deliver as many parcels on time as possible." Here are six parcels, as hours and deadline.
| Parcel | A | B | C | D | E | F |
|---|---|---|---|---|---|---|
| Hours | 4 | 2 | 5 | 5 | 4 | 6 |
| Deadline | 17 | 16 | 5 | 8 | 6 | 10 |
Sort the parcels by deadline: C (5), E (6), D (8), F (10), B (16), A (17). Keep the parcels you have taken in a max-heap of their hours, so the longest is on top. Keep a clock: the total hours of the kept parcels.
For each parcel, add it to the heap and add its hours to the clock. If the clock is now past the parcel's deadline, give back the kept parcel with the most hours.
| Parcel | Hours and deadline | Clock after adding | Past the deadline? | Given back | Kept parcels (hours) | Clock |
|---|---|---|---|---|---|---|
| C | 5, due 5 | 5 | no | none | 5 | 5 |
| E | 4, due 6 | 9 | yes: 9 is past 6 | C (5 hours) | 4 | 4 |
| D | 5, due 8 | 9 | yes: 9 is past 8 | D (5 hours) | 4 | 4 |
| F | 6, due 10 | 10 | no: 10 is not past 10 | none | 4, 6 | 10 |
| B | 2, due 16 | 12 | no | none | 2, 4, 6 | 12 |
| A | 4, due 17 | 16 | no | none | 2, 4, 4, 6 | 16 |
Four parcels are on time: E, F, B and A, in 16 hours. At parcel E the courier gave back C, a parcel that looked fine when it arrived. At parcel D the new parcel itself was the longest, so it was the one given back.
Sort the parcels by deadline, add each one, and when the clock is past its deadline give back the kept parcel with the most hours.
Now look at two rules that never give a parcel back.
| Rule | Parcels it keeps | Count |
|---|---|---|
| Take a parcel only if it fits, never give back | C, B, A | 3 |
| Shortest parcel first (ties by deadline), take it if it fits | B, E, A | 3 |
| Sort by deadline, give back the longest | E, F, B, A | 4 |
Taking C first looks harmless. It uses 5 hours that E, D and F need, and C then blocks all three. Giving it back is the only way out, and a rule that never gives back cannot do it.
The step player below cannot draw a heap yet. It replays the rule of the last lesson, earliest finish, on ride requests with fixed start and end hours. It goes through one fixed order, takes or skips each request, and never gives one back.
For rides with fixed hours that is enough, as the last lesson proved. A parcel has no fixed hour, so an early choice can block later ones, and that is why parcels need the give-back. Watch how every step of the baseline is final.
Step by step: Earliest finish first on the evening's requests. The animated player loads in your browser.
Predict what happens
Q The kept parcels take 9 hours, and the next parcel is due at hour 6 and takes 4 hours. The clock is 13 after adding it. What does the rule do?
Answer: B
The clock is past the new parcel's deadline, so the rule gives back the kept parcel with the most hours. The new parcel may itself be the longest, and then it is the one that goes.
Pick a list of ride requests, and step through the baseline rule forwards and back. The panel at the end shows how many requests the rule took and how many the best plan has.
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
The rule rests on two facts. The first is about order. A set of parcels can all be on time if and only if they are on time when done in the order of their deadlines.
Here is why. Suppose a parcel X with a later deadline is done right before a parcel Y with an earlier deadline. Swap them. Y now finishes earlier, so it is on time.
X now finishes when Y used to finish. That was no later than Y's deadline, which is no later than X's. So the swap never makes a parcel late, and the sorted order is the best order.
After each parcel, the kept parcels are an on-time set as large as any other. Their k-th shortest parcel is never longer than the k-th shortest parcel of any other on-time set.
The second fact is about the give-back. Suppose the clock passes the deadline of the new parcel. The kept parcels were on time before, and the new parcel has the latest deadline so far. So the only problem is the new parcel's own deadline, and removing any parcel with at least as many hours as the new one fixes it.
Let K be the kept parcels, p the new parcel and q the longest parcel of K and p together. Remove q.
If q is p, what is left is K, which was on time.
If q is in K, the clock becomes the total of K plus the hours of p, minus the hours of q. That is at most the total of K, because q is at least as long as p. The total of K was at most the deadline of the last kept parcel, which is at most the deadline of p. So p is on time, and every parcel before it finishes no later than before.
Removing the longest parcel takes the most time off the clock, so no other removal leaves a smaller total.
Call a set dominating when it is as large as any on-time set. Also, its k-th shortest parcel must never be longer than the k-th shortest parcel of any on-time set of at least k parcels. Dominating means largest, and among the largest sets, the fewest hours.
Claim: after each parcel, the kept set dominates every on-time set made from the parcels seen so far. We go by the number of parcels, and the first step is clear: one parcel, kept if it fits alone.
Take the new parcel p, with the latest deadline so far, and an on-time set S from the parcels so far. If S does not contain p, the old kept set dominated S. The new kept set dominates the old one, because it adds p, swaps the longest for a p that is not longer, or gives p straight back.
If S contains p, remove p from S and call what is left S'. The old kept set K dominates S'. There are two cases.
In the late case, S' is smaller than K. If the longest parcel given back is in K, the smallest parcels of K, plus p, are still in the new kept set, so it dominates S.
If p itself is given back, the new kept set is K, and no parcel of K is longer than p. The k-th shortest parcel of S is then either at least p or the k-th shortest of S'. In both cases the k-th shortest of K is no longer, so K dominates S.
So the rule is safe at every step, and the end result is a best set. We also ran it against a brute force that tries every order of every set, on 20,000 random lists of up to 6 parcels. They agreed every time, on the count and on the hours.
Predict what happens
Q The kept parcels are 2 and 4 hours. A new parcel of 3 hours is due so early that the clock, 9, is past its deadline. Which parcel is given back?
Answer: C
The rule gives back the kept parcel with the most hours, which is the one of 4 hours. Removing it leaves a clock of 5 and keeps the new parcel of 3.
Here is the rule as code. most_parcels_on_time returns how many parcels can be on time. The markers [1] to [4] match the steps above.
import heapq
def most_parcels_on_time(parcels):
# [1] Sort by deadline: the parcel due first comes first.
order = sorted(parcels, key=lambda parcel: parcel[1])
# [2] The kept parcels wait in a max-heap of their hours, and the clock is their total hours.
# Python's heap is a min-heap, so it stores negated hours.
kept = []
clock = 0
for hours, deadline in order:
# [3] Add the parcel: the courier would finish it after all the kept ones.
heapq.heappush(kept, -hours)
clock += hours
# [4] Past the deadline? Give back the kept parcel with the most hours.
if clock > deadline:
clock += heapq.heappop(kept)
return len(kept)public int mostParcelsOnTime(int[][] parcels) {
// [1] Sort by deadline: the parcel due first comes first.
int[][] order = parcels.clone();
java.util.Arrays.sort(order, (a, b) -> Integer.compare(a[1], b[1]));
// [2] The kept parcels wait in a max-heap of their hours, and the clock is their total hours.
java.util.PriorityQueue<Integer> kept = new java.util.PriorityQueue<>(java.util.Collections.reverseOrder());
long clock = 0;
for (int[] parcel : order) {
// [3] Add the parcel: the courier would finish it after all the kept ones.
kept.add(parcel[0]);
clock += parcel[0];
// [4] Past the deadline? Give back the kept parcel with the most hours.
if (clock > parcel[1]) clock -= kept.poll();
}
return kept.size();
}int mostParcelsOnTime(vector<vector<int>> parcels) {
// [1] Sort by deadline: the parcel due first comes first.
sort(parcels.begin(), parcels.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
// [2] The kept parcels wait in a max-heap of their hours, and the clock is their total hours.
// The default priority_queue is a max-heap.
priority_queue<int> kept;
long long clock = 0;
for (auto& parcel : parcels) {
// [3] Add the parcel: the courier would finish it after all the kept ones.
kept.push(parcel[0]);
clock += parcel[0];
// [4] Past the deadline? Give back the kept parcel with the most hours.
if (clock > parcel[1]) {
clock -= kept.top();
kept.pop();
}
}
return (int)kept.size();
}// JavaScript has no built-in heap, so here is a small binary heap: before(a, b) is true when a belongs nearer the top than b.
class Heap {
constructor(before) { this.a = []; this.before = before; }
size() { return this.a.length; }
peek() { return this.a[0]; }
push(x) {
const a = this.a;
a.push(x);
let i = a.length - 1;
while (i > 0) {
const p = (i - 1) >> 1;
if (!this.before(a[i], a[p])) break;
[a[i], a[p]] = [a[p], a[i]];
i = p;
}
}
pop() {
const a = this.a;
const top = a[0];
const last = a.pop();
if (a.length > 0) {
a[0] = last;
let i = 0;
for (;;) {
let c = 2 * i + 1;
if (c >= a.length) break;
if (c + 1 < a.length && this.before(a[c + 1], a[c])) c++;
if (!this.before(a[c], a[i])) break;
[a[i], a[c]] = [a[c], a[i]];
i = c;
}
}
return top;
}
}
function mostParcelsOnTime(parcels) {
// [1] Sort by deadline: the parcel due first comes first.
const order = [...parcels].sort((a, b) => a[1] - b[1]);
// [2] The kept parcels wait in a max-heap of their hours, and the clock is their total hours.
const kept = new Heap((a, b) => a > b);
let clock = 0;
for (const [hours, deadline] of order) {
// [3] Add the parcel: the courier would finish it after all the kept ones.
kept.push(hours);
clock += hours;
// [4] Past the deadline? Give back the kept parcel with the most hours.
if (clock > deadline) clock -= kept.pop();
}
return kept.size();
}On the six parcels this returns 4. When two kept parcels have equal hours, either may be given back: the count and the clock are the same.
Exercise · Find the bug: The clock that forgets a parcel. This rule sorts by deadline and gives back the longest kept parcel when the clock passes a deadline. It keeps too few parcels on some lists. Which line is wrong?
import heapq
def most_parcels_on_time(parcels):
order = sorted(parcels, key=lambda parcel: parcel[1])
kept = []
clock = 0
for hours, deadline in order:
heapq.heappush(kept, -hours)
clock += hours
if clock > deadline:
heapq.heappop(kept)
return len(kept)Now write it yourself. The lab has one function, plan_parcels(parcels). It returns two numbers: how many parcels can be on time, and the total hours of the kept parcels.
For the six parcels the answer is [4, 16]. For no parcels it is [0, 0].
The second number is what the clock holds at the end. The dominating argument shows it is the fewest hours of any set with that many parcels.
Three rules keep it correct:
clock > deadline.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Try every order of every set | Sort, then keep a heap |
|---|---|---|
| Time to choose | O(2^n × n): a table over sets, with every parcel as the last one | O(n log n) to sort, then O(log n) for each parcel |
| Steps for 20 parcels | about 21 million set and last-parcel pairs | about 20 × 4.3 = 86 comparisons to sort, then 20 heap steps |
| Memory | O(2^n) for the table | O(n) for the heap |
| Why it is right | Every set is checked | A safe rule: the dominating argument |
For 100,000 parcels the sort is about 100,000 × 17 = 1.7 million steps, and the heap adds about the same. The clock stays below the largest deadline plus one parcel. That is below 2 × 10^9 when each value is at most 10^9, so a 64-bit clock is a safe habit.
The same idea has four forms. Each of the practice problems uses one of them.
| Form | The heap holds | What it gives back or takes | Practice problem |
|---|---|---|---|
| Keep the k best | The k best items so far | The smallest, when a new item beats it | Best score from two paired lists (best-score-from-paired-lists) |
| Give back when a limit is passed | The items taken so far | The worst one, when a total goes over | Furthest building reach (furthest-building-reach) |
| Take the best allowed item | The items that can be taken now | The best one, then the next unlocked ones are added | Maximise capital before the deadline (maximise-capital-before-the-deadline) |
| Pretend a choice only when forced | The choices you passed | The best one, when you run out | Minimum refuel stops (minimum-refuel-stops) |
Three more problems use the heap as a plain priority list. They are Smallest cost to connect ropes (smallest-cost-to-connect-ropes), Take gifts from the richest pile (take-gifts-from-the-richest-pile) and Fewest halvings to cut the load (fewest-halvings-to-cut-the-load). Maximum performance of a team (maximum-performance-of-a-team) is the keep-the-k-best form again.
Use greedy with a heap when items arrive in a fixed order and a limit stops you from keeping them all. The worst item must be found by one rule. Then keep the items in a heap, and give back the worst one when the limit is hit.
Typical fits are the k best items of a stream, the most jobs before their deadlines, and joining items where each join creates a new item. Words such as "the k largest", "the fewest steps" and "the best one allowed now" are hints. A sort is often the first step, and the heap handles the rest.
Do not use it when a choice cannot be given back, for example a ride already driven. Do not use it when no single rule decides what to give back. A knapsack, where value and weight both matter, is one case. Use dynamic programming there.
If the input is tiny, sorting and trying every set is fine. If the whole input is known and you only need the k largest, a selection method such as quickselect finds them in O(n) time on average.
if clock + hours <= deadline: take it looks natural, but it never gives a parcel back. On the parcels [[5, 10], [6, 6], [4, 9]], as hours and deadline, it takes the parcel of 6 hours due at 6 and then nothing else fits. It keeps 1 parcel. The best is 2: the parcels of 6 and 4 hours do not both fit, but 4 and 5 hours do, finishing at hour 9.
A rule that takes a parcel if it fits and never gives one back keeps one parcel here. The best is two.
order = sorted(parcels) puts the shortest parcel first. On [[4, 13], [6, 9]] it does the 4-hour parcel first, and then the 6-hour parcel finishes at hour 10, past its deadline of 9. It keeps 1 parcel. The best is 2: the 6-hour parcel first, then the 4-hour one, finishing at hour 10 by the deadline of 13.
Using a min-heap by mistake gives back the parcel with the fewest hours. On [[5, 10], [6, 6], [4, 9]] the clock after the second parcel is 10, past 9, and the rule gives back the 4-hour parcel. It then keeps 1 parcel. Give back the longest, with a max-heap.
Going through the parcels in the order of the list breaks the rule. On [[5, 9], [2, 6]] the parcel of 5 hours comes first, and then the parcel of 2 hours is late. The rule keeps 1 parcel. After sorting by deadline, the parcel of 2 hours comes first and both fit, so the answer is 2.
Predict what happens
Q Three parcels take 3 hours each and are due at hours 3, 6 and 9. How many parcels can be on time?
Answer: C
Sorted by deadline, the clock is 3, 6 and 9, and each parcel finishes exactly at its deadline. A parcel that finishes at its deadline is on time, so nothing is given back and all 3 are kept.
Explain the give-back in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The idea
Q1/2 What does greedy with a heap keep in the heap?
Answer: B
The heap holds the choices taken so far. When a limit is reached, the worst one is on top, and it is the one given back.
Q2/2 You keep the 3 largest fares of a stream. Which kind of heap do you use?
Answer: B
The fare you give back is the smallest of the three, and a min-heap shows the smallest item on top. The heap then holds the three largest fares.
Checkpoint · Keeping the k best
Q1/2 The heap holds the fares 5, 8 and 9, with k = 3. A fare of 12 arrives. What is the total after it?
Answer: B
The new fare beats the smallest fare, 5, so 5 is given back. The heap holds 8, 9 and 12, and the total is 29.
Q2/2 A fare of 4 arrives when the heap holds 8, 9 and 12 with k = 3. What happens?
Answer: C
The fare 4 is smaller than every fare in the heap, so after it is pushed it is the smallest, and it is the one given back. The heap stays 8, 9 and 12.
Checkpoint · Parcels with deadlines
Q1/2 Parcels have hours and a deadline. What is the first step of the rule for the most on-time parcels?
Answer: B
The rule goes through the parcels in the order of their deadlines. A set can be on time exactly when it is on time in that order.
Q2/2 The clock passes the deadline of the parcel added last. Which kept parcel is given back?
Answer: C
The longest kept parcel takes the most time off the clock, and what is left is on time. The new parcel is among the candidates.
Checkpoint · Rules that fail
Q1/2 Parcels are 5 hours due at 10, 6 hours due at 6 and 4 hours due at 9. A rule takes a parcel only if it fits, and never gives one back. How many does it keep?
Answer: C
Sorted by deadline, it takes the parcel of 6 hours first. Then 6 + 4 is 10, past 9, and 6 + 5 is 11, past 10. It keeps 1. The best is 2, with the parcels of 4 and 5 hours.
Q2/2 Parcels are 4 hours due at 13 and 6 hours due at 9. Doing the shortest parcel first keeps one parcel. What is the best?
Answer: B
The 6-hour parcel finishes at hour 6, on time. The 4-hour parcel then finishes at hour 10, before its deadline of 13. The shortest-first order makes the 6-hour parcel finish at hour 10, past 9.
Checkpoint · Cost and use
Q1/2 What is the running time of sort-by-deadline with a heap on n parcels?
Answer: C
The sort costs O(n log n), and each parcel is one push and at most one pop, each O(log n). So the total is O(n log n).
Q2/2 A courier route must reach a destination, and you may stop at stations you have already passed. Which form of the idea is it?
Answer: B
You decide to stop only when the range runs out, and then you pick the best passed station from a max-heap. The refuel-stops problem works this way.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.