Pick the sort key that makes a greedy rule safe, prove it with an exchange argument, and remove or chain intervals by their ends.
You work on the booking page of a shared meeting room. Eight requests arrived for one day, and each has a start hour and an end hour. Your team lead says: "We cannot double-book. Cancel as few requests as possible, so that no two requests overlap."
| Request | Starts | Ends |
|---|---|---|
| A | 11 | 13 |
| B | 10 | 12 |
| C | 8 | 13 |
| D | 14 | 15 |
| E | 12 | 14 |
| F | 15 | 20 |
| G | 8 | 11 |
| H | 9 | 10 |
Two requests overlap when they share some time. A request that starts at 12 can follow a request that ends at 12, because they only touch. Cancelling the fewest requests means keeping the most, so the job is the same as before: find the largest set of requests with no overlap.
The first attempt is correct. Try every set of requests, drop the sets that contain an overlap, and keep the largest. Eight requests make 2^8 = 256 sets, which is nothing for a computer.
Every extra request doubles the number of sets. With 40 requests there are 2^40 = 1,099,511,627,776 sets, so the first attempt stops being usable. Last lesson you saw that sorting by end time gives a safe rule for talks. This time we ask a bigger question: how do you find the sort key for a new problem, and how do you know it is safe?
A station has one platform. Each train needs it from its arrival until its departure, and two trains cannot stand there together. The station manager wants to serve as many trains as possible.
She looks at the departure times. The train that leaves first frees the platform soonest, so it leaves the most room for the trains after it. She serves that train, then looks for the next train that arrives after it has left.
The trains are the requests, the platform is the room, and the departure time is the end hour. The picture hides one thing: it does not say why the earliest departure is safe. The exchange test in section 3 gives the reason, and it works for other keys as well.
A station platform: the train that leaves first frees the platform soonest. The picture does not say why that rule is safe.
A greedy algorithm by sorting puts the choice in the sort order. After the sort, the best choice is always the next item, so one pass is enough. All the work is in finding the key, and the key depends on the goal.
Predict what happens
Q You keep request H (9 to 10). Request B runs from 10 to 12. Can you keep both?
Answer: B
Two requests overlap only when they share some time. H uses 9:00 until 10:00 and B uses 10:00 until 12:00, so they share none. Touching at 10 is allowed.
Each rule is greedy in the same way. It goes through the requests in its own order, keeps a request when it overlaps none that are already kept, and skips it otherwise. Only the order changes. Run the three rules on the eight requests.
| Rule | Requests it keeps | Kept | Cancelled |
|---|---|---|---|
| Earliest start first | C (8 to 13), D (14 to 15), F (15 to 20) | 3 | 5 |
| Shortest first | D (14 to 15), H (9 to 10), A (11 to 13), F (15 to 20) | 4 | 4 |
| Earliest end first | H (9 to 10), B (10 to 12), E (12 to 14), D (14 to 15), F (15 to 20) | 5 | 3 |
Only one rule finds the best plan, and the best plan cancels 3 requests. Earliest start keeps C, a 5-hour request that overlaps G, H, B, A and E. Shortest first keeps A, which sits across the end of B and the start of E, so it blocks both. Earliest end first keeps the request that frees the room soonest every time.
Exercise · Break it: Find the requests that shortest-first mishandles. This plan keeps the shortest requests first, and a request only if it overlaps none already kept. Find a list of requests where it keeps fewer than the best plan.
def most_kept(requests):
order = sorted(requests, key=lambda r: r[1] - r[0])
kept = []
for start, end in order:
if all(end <= s or start >= e for s, e in kept):
kept.append([start, end])
return len(kept)Sort the requests by end time: H (10), G (11), B (12), A (13), C (13), E (14), D (15), F (20). A and C both end at 13, so their order follows the list. Keep one number, the end of the last request kept, and start it at 0.
| Request | Starts and ends | Last end before | Fits? | Last end after | Kept so far |
|---|---|---|---|---|---|
| H | 9 to 10 | 0 | yes | 10 | 1 |
| G | 8 to 11 | 10 | no | 10 | 1 |
| B | 10 to 12 | 10 | yes | 12 | 2 |
| A | 11 to 13 | 12 | no | 12 | 2 |
| C | 8 to 13 | 12 | no | 12 | 2 |
| E | 12 to 14 | 12 | yes | 14 | 3 |
| D | 14 to 15 | 14 | yes | 15 | 4 |
| F | 15 to 20 | 15 | yes | 20 | 5 |
A request fits when it starts at or after the last end. Five requests stay, and 8 - 5 = 3 are cancelled. After the sort, "the request that ends first among those that fit" is the next request in the list that fits.
Exercise · Predict the output: What does the room scan end with?. Five requests are sorted by end time and scanned with the rule above. The program prints how many it kept and the last end. What does it print?
requests = [[10, 12], [9, 11], [12, 13], [11, 14], [13, 15]]
free_at = 0
kept = 0
for start, end in sorted(requests, key=lambda r: r[1]):
if start >= free_at:
kept += 1
free_at = end
print(kept, free_at)Sort by end time, then scan once: keep a request when it starts at or after the last end, and skip it otherwise.
Step by step: Earliest finish first on the eight requests. The animated player loads in your browser.
Now watch the rule that fails. Earliest start takes C first, and then almost everything overlaps it.
Step by step: Earliest start first on the eight requests. The animated player loads in your browser.
Predict what happens
Q You have kept H and B, so the last end is 12. The next request in the sorted list is A (11 to 13). What does the rule do?
Answer: B
A request fits only when it starts at or after the last end. A starts at 11, before 12, so it overlaps B and is skipped. The scan goes on to C.
Pick a list of requests and a rule, then step through it forwards and back. The panel at the end shows how many requests the rule kept and how many the best plan keeps.
Try these four, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Last lesson gave two proofs for the end-time rule. This lesson uses the exchange argument as a method for finding the key. The method has four steps.
Swap the greedy choice into any best answer. If the answer stays valid and no worse, the key is safe, and one pass in that order finishes the job.
Take any best plan, and call its first request X. Let g be the request that ends first of all. Then g ends no later than X, so replace X with g. The next request in the plan starts at or after the end of X, so at or after the end of g.
The plan is still valid and has the same size, so it is still a best plan, and it now starts with g. Drop the requests that overlap g and repeat on the rest. The key is the end time, and the swap shows why.
A print service runs jobs one after another on one printer. Each job has a length in minutes and a weight, which says how much a minute of waiting costs for that job. The cost of a job is its weight times the minute it finishes, and the service wants the lowest total.
Take four jobs, written as (length, weight): P1 (4, 9), P2 (3, 6), P3 (8, 2) and P4 (1, 8). Three natural rules give three different totals.
| Order rule | Order | Total cost |
|---|---|---|
| Shortest length first | P4, P2, P1, P3 | 136 |
| Heaviest weight first | P1, P4, P2, P3 | 156 |
| Length divided by weight, smallest first | P4, P1, P2, P3 | 133 |
Trying all 24 orders confirms that 133 is the lowest total. Now find the key with the exchange test. Take two neighbouring jobs a and b, with the printer free at minute t. Write l for a length and w for a weight.
Subtract the second from the first. The terms with t cancel, and so do w_a × l_a and w_b × l_b. What is left is w_b × l_a - w_a × l_b.
So a first is no worse exactly when l_a × w_b is at most l_b × w_a. That is the same as l_a divided by w_a being at most l_b divided by w_b. The key is length divided by weight. For P1 and P2 the change is 6 × 4 - 9 × 3 = -3, so running P1 first saves 3.
Now take any order, best or not. If two neighbours are out of key order, swapping them changes the cost by a number that is at most zero. Repeat until no such pair is left: the cost never rises, and the order is now the key order. So the key order costs no more than any order, and it is a best order.
Jobs with equal keys can swap at no cost, so every key order gives the same total. To avoid rounding, compare a and b by a.length * b.weight against b.length * a.weight.
Swap two neighbouring print jobs and subtract the costs: what is left is a small formula, and its sign gives the sort key.
Predict what happens
Q Job a has length 2 and weight 1. Job b has length 3 and weight 9. Which should run first?
Answer: B
The cost of a first is 1 × 2 + 9 × 5 = 47. The cost of b first is 9 × 3 + 1 × 5 = 32. The heavier job goes first, which is what the ratio says.
The same test finds a key built from two numbers. Candidates go to office A or office B, half to each, and each has a cost for each office.
Start with everyone at B. Moving one candidate to A changes the total by cost_a - cost_b. We must move exactly half, so the best choice is the half with the smallest change.
For the costs (30, 20), (200, 300), (100, 110) and (400, 50) the changes are 10, -100, -10 and 350. Sending the two smallest changes to A gives 200 + 100 + 20 + 50 = 370, the lowest total. The key is the difference, and the swap of two candidates changes the total by one difference minus the other.
Exercise · Put it in order: Half to each office. Arrange the lines into a function that returns the lowest total when exactly half of the candidates go to office A and the rest to office B. Each candidate is [cost_a, cost_b].
def cheapest_split(costs):
order = sorted(costs, key=lambda c: c[0] - c[1])
half = len(costs) // 2
total = 0
for i in range(len(order)):
if i < half:
total += order[i][0]
else:
total += order[i][1]
return total
order = sorted(costs, key=lambda c: c[0])Sometimes sorting alone does not settle the choice, and a count does. A list of numbers must be cut into batches of 3 consecutive numbers, such as 11, 12, 13. Take 12, 11, 13, 12, 14, 13.
The smallest number left must start a batch, because nothing smaller remains to come before it. For 11 the batch is 11, 12, 13.
Then 12 is the smallest left, and its batch is 12, 13, 14. Every number is used, so the answer is yes. Counts handle repeated numbers: a number that appears twice starts two batches.
| Question | Key | What the swap shows |
|---|---|---|
| Most units under a limit | Units per box, largest first | A better box for a worse one: same room, more units |
| Most requests with no overlap | End time, smallest first | An earlier end never blocks more |
| Lowest weighted waiting | Length divided by weight | The change is w_b × l_a - w_a × l_b |
| Half to each of two offices | cost_a - cost_b | The change is one difference minus the other |
Predict what happens
Q You swap two neighbouring print jobs and the total always goes up or stays the same. What does that tell you?
Answer: B
If no swap of neighbours can improve the order, then sorting by the key reaches a best order. This is the exchange argument used as a method.
Here is the end-time rule as code. most_kept returns the number of requests in a best plan. The step markers [1] to [4] match the steps above.
def most_kept(requests):
# [1] Sort by end time: the request that ends first comes first.
order = sorted(requests, key=lambda r: r[1])
# [2] Nothing is kept yet, so the room is free from the start of the day.
free_at = 0
kept = 0
for start, end in order:
# [3] A request fits when it starts at or after the end of the last request kept.
if start >= free_at:
# [4] Keep it. The room is busy until it ends.
kept += 1
free_at = end
return keptpublic int mostKept(int[][] requests) {
// [1] Sort by end time: the request that ends first comes first.
int[][] order = requests.clone();
java.util.Arrays.sort(order, (a, b) -> Integer.compare(a[1], b[1]));
// [2] Nothing is kept yet, so the room is free from the start of the day.
int freeAt = 0;
int kept = 0;
for (int[] request : order) {
// [3] A request fits when it starts at or after the end of the last request kept.
if (request[0] >= freeAt) {
// [4] Keep it. The room is busy until it ends.
kept++;
freeAt = request[1];
}
}
return kept;
}int mostKept(vector<vector<int>> requests) {
// [1] Sort by end time: the request that ends first comes first.
sort(requests.begin(), requests.end(), [](const vector<int>& a, const vector<int>& b) { return a[1] < b[1]; });
// [2] Nothing is kept yet, so the room is free from the start of the day.
int freeAt = 0;
int kept = 0;
for (auto& request : requests) {
// [3] A request fits when it starts at or after the end of the last request kept.
if (request[0] >= freeAt) {
// [4] Keep it. The room is busy until it ends.
kept++;
freeAt = request[1];
}
}
return kept;
}function mostKept(requests) {
// [1] Sort by end time: the request that ends first comes first.
const order = [...requests].sort((a, b) => a[1] - b[1]);
// [2] Nothing is kept yet, so the room is free from the start of the day.
let freeAt = 0;
let kept = 0;
for (const [start, end] of order) {
// [3] A request fits when it starts at or after the end of the last request kept.
if (start >= freeAt) {
// [4] Keep it. The room is busy until it ends.
kept++;
freeAt = end;
}
}
return kept;
}On the eight requests this returns 5, so the answer to the team lead is 8 - 5 = 3 cancellations. When two requests end at the same hour, either may come first, because only one of them can be kept.
Exercise · Find the bug: The request that overlaps but stays. This scan sorts by end time, yet it keeps requests that overlap. Which line is wrong?
def most_kept(requests):
order = sorted(requests, key=lambda r: r[1])
free_at = 0
kept = 0
for start, end in order:
if end >= free_at:
kept += 1
free_at = end
return keptNow write it yourself. The lab has two functions, one for each key you have met.
plan_room(requests) returns two numbers: how many requests can stay, and how many must be cancelled. For the eight requests the answer is [5, 3].lowest_weighted_wait(jobs) returns the lowest total of weight times finish minute for print jobs given as [length, weight]. For the four jobs above the answer is 133.Three rules keep it correct:
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
| Question | Try every set or order | Sort by the key, then scan |
|---|---|---|
| Time to choose | O(2^n × n) for sets, O(n! × n) for orders | O(n log n) to sort, then O(n) for the scan |
| Steps for 40 requests | about 1.1 trillion sets | about 40 × 5.3 = 213 comparisons to sort, then 40 steps |
| Memory | O(n) for one set at a time | O(n) for the sorted copy |
| Why it is right | Every set is checked | A safe key: the exchange test |
For 100,000 items, the sort is about 100,000 × 17 = 1.7 million comparisons, and the scan is 100,000 steps. The sort is the expensive part, and the choice itself costs almost nothing.
Use greedy by sorting when the goal is a total or a count and the items share one limit. You must also be able to name what the order should decide. Then run the exchange test on two neighbours and see whether the change is never bad.
Typical fits are loading by value, keeping the most non-overlapping requests, ordering jobs by weighted waiting, and splitting between two sites by a difference.
Words such as "most", "fewest", "lowest total" and "exactly half" are hints. Write the swap before you write the code.
Do not use the end-time rule when each request also has a value and you want the largest total value. Take A (9 to 17) worth 10, B (9 to 12) worth 1 and C (12 to 17) worth 1. Sorting by end keeps B and C, for a value of 2, while A alone is worth 10.
The swap in the proof no longer holds, because replacing A by an earlier request loses value. For weighted requests you need dynamic programming. If the input is tiny, the first attempt that tries every set is fine, and it has no proof to get wrong.
order = sorted(requests, key=lambda r: r[0]) looks natural, but on the eight requests it keeps C, D and F: 3 kept and 5 cancelled. The best plan cancels 3. A request that starts early can end late, and it blocks everything inside it. Sort by end time.
Sorting by start time keeps C first, and C overlaps five requests, so only three stay while the best plan keeps five.
if start > free_at: rejects a request that starts exactly when the last one ends. On [[9, 10], [10, 11]] it keeps only the first and cancels 1. The right answer cancels 0, because the second can follow the first. Use >=.
key=lambda j: j[0] // j[1] divides whole numbers, so 1 over 2 and 1 over 3 both become 0 and look equal. On the jobs [[1, 2], [1, 3]] the list order is kept, and the total is 1 × 2 + 2 × 3 = 8. Running the heavier job first gives 1 × 3 + 2 × 2 = 7. Compare a[0] * b[1] with b[0] * a[1].
Writing free_at = end outside the if moves the last end even when the request was skipped. On [[9, 11], [10, 12], [11, 13]] the request from 10 to 12 is skipped but the last end becomes 12, so the request from 11 to 13 is skipped as well. The result keeps 1 request. The right answer keeps 2: the requests from 9 to 11 and from 11 to 13.
For the numbers [4, 3] in batches of 2, the rule start = numbers[0] begins at 4, needs a 5, and answers no. The smallest number is 3, and the batch 3, 4 makes the answer yes. The smallest number left must start the batch.
Explain the exchange test 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 · What the sort does
Q In a greedy by sorting, what does the sort do?
Answer: B
After the sort by the right key, the best choice is always the next item, so one pass applies it. The sort does not prove anything: the key still needs an exchange test.
Checkpoint · Fewest to cancel
Q Requests are [1, 3], [2, 4] and [3, 5], and touching is allowed. What is the fewest to cancel?
Answer: B
Sort by end: [1, 3] is kept, [2, 4] starts before 3 and is skipped, [3, 5] starts at 3 and is kept. Two stay, so 3 - 2 = 1 is cancelled.
Checkpoint · Touching
Q Requests are [1, 2], [2, 3] and [3, 4], and a request that starts when another ends does not overlap it. How many are cancelled?
Answer: A
Each request starts exactly when the one before ends. They only touch, so all three stay and none is cancelled. The test is start at least the last end.
Checkpoint · The exchange test
Q What does the exchange test do?
Answer: A
The exchange test swaps two neighbours and computes the change. If the change is never bad, the order is safe, and the sign of the change gives the key.
Checkpoint · Weighted waiting
Q Job a has length 2 and weight 3. Job b has length 4 and weight 1. Which order has the lower total of weight times finish minute?
Answer: B
Running a first costs 3 × 2 + 1 × 6 = 12. Running b first costs 1 × 4 + 3 × 6 = 22. The key length divided by weight is 2/3 for a and 4 for b, so a goes first.
Checkpoint · The key
Q Which key gives the lowest total of weight times finish minute?
Answer: C
Swapping neighbours a and b changes the total by w_b × l_a - w_a × l_b. So a goes first when l_a over w_a is at most l_b over w_b.
Checkpoint · Rounding
Q Why compare print jobs by cross-multiplying instead of dividing whole numbers?
Answer: B
1 divided by 2 and 1 divided by 3 are both 0 in whole numbers. The jobs [1, 2] and [1, 3] would then keep their list order and cost 8, while the heavier job first costs 7.
Checkpoint · Two prices
Q Costs to office A and B are (10, 30) and (40, 20), and one candidate goes to each office. What is the lowest total?
Answer: A
The differences cost_a - cost_b are -20 and 20. Send the candidate with -20 to A for 10, and the other to B for 20. The total is 30.
Checkpoint · Forced start
Q A list is [2, 3, 3, 4, 5, 5], cut into batches of 3 consecutive numbers. What is the answer?
Answer: C
The smallest number left must start a batch. After 2, 3, 4 the numbers 3, 5, 5 remain. The batch from 3 needs a 4, and there is none.
Checkpoint · A value of its own
Q A (9 to 17) is worth 10, B (9 to 12) is worth 1 and C (12 to 17) is worth 1. You want the most value. What does the end-time rule give?
Answer: B
Sorted by end, B ends first and C follows, so the rule keeps B and C for a value of 2. A alone is worth 10, so with values the end-time rule fails and you need dynamic programming.
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.