Sub topic 7
Activity Selection: Earliest Finish Time First
This chapter assumes you can read Python with loops and sorting, know that sorting costs O(n log n), and have seen the greedy-stays-ahead proof technique from the earlier chapter. Here you apply that technique to its classic first problem.
The problem
You have one resource, such as a lecture hall, a CPU core, or a meeting room. You also have a list of requests. Each request is an interval (start, end). Two requests are compatible if they do not overlap. The goal is to pick the largest possible set of mutually compatible requests.
The goal is the number of requests. Total time used does not count, and neither does which requests get picked. This detail matters later, because changing the goal to total value breaks the greedy approach.
Throughout this chapter, intervals are half-open: (s, e) covers times s up to but not including e. So (1, 4) and (4, 7) are compatible, because one ends exactly when the other starts.
Choosing the greedy rule
A greedy algorithm needs a rule for which interval to take next. Several rules sound reasonable. Most of them are wrong.
| Rule | Intuition | Counterexample | Greedy picks | Optimal |
|---|---|---|---|---|
| Earliest start | Start using the room early | `(0,10), (1,2), (3,4)` | 1 (`(0,10)`) | 2 |
| Shortest duration | Short requests block less | `(0,5), (4,7), (6,11)` | 1 (`(4,7)`) | 2 |
| Fewest conflicts | Avoid requests that block many others | 13-interval instance below | 3 | 4 |
| Earliest finish | Free the room as soon as possible | none exists | optimal | optimal |
Earliest finish works because of what it leaves behind. The interval that ends first leaves the most time for everything else. Any other first choice ends at the same time or later, so it can only shrink the set of requests still available.
The fewest-conflicts rule is the hardest to rule out. Small cases seem to work, so you need a built-out counterexample. The code below builds one and runs both rules on it.
def overlaps(p, q):
return p[0] < q[1] and q[0] < p[1]
def fewest_conflicts(intervals):
remaining = list(intervals)
chosen = []
while remaining:
scores = [
sum(overlaps(iv, other) for j, other in enumerate(remaining) if j != i)
for i, iv in enumerate(remaining)
]
best = remaining[scores.index(min(scores))]
chosen.append(best)
remaining = [iv for iv in remaining if not overlaps(iv, best)]
return chosen
def select_activities(intervals):
chosen = []
last_end = float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]):
if start >= last_end:
chosen.append((start, end))
last_end = end
return chosen
row = [(0, 4), (4, 8), (8, 12), (12, 16)]
instance = row + [(3, 5)] * 4 + [(7, 9)] + [(11, 13)] * 4
print(len(fewest_conflicts(instance))) # 3
print(len(select_activities(instance))) # 4The interval (7, 9) conflicts with only two others, so fewest-conflicts takes it first. That one choice removes both (4, 8) and (8, 12) from the optimal row, and the algorithm never recovers.
The algorithm
- Sort the intervals by finish time.
- Track
last_end, the finish time of the most recently chosen interval. It starts at negative infinity. - Scan the intervals in sorted order. Take an interval if its start is at or after
last_end, then updatelast_end.
def select_activities(intervals):
chosen = []
last_end = float("-inf")
for start, end in sorted(intervals, key=lambda iv: iv[1]):
if start >= last_end:
chosen.append((start, end))
last_end = end
return chosen
print(select_activities([(1, 4), (3, 5), (0, 6), (5, 7), (3, 9), (5, 9), (6, 10), (8, 11)]))
# [(1, 4), (5, 7), (8, 11)]Here is the trace for that input. After sorting, the sces (1, 4) and sets last_end = 4. It rejects (3, 5) and (0, 6) because they start before 4. It takes (5, 7) and sets last_end = 7. It rejects (3, 9), (5, 9) and (6, 10). It takes (8, 11).
Complexity
Sorting costs O(n log n). The scan costs O(n) and uses O(1) extra state besides the output. If the input already arrives sorted by finish time, as it does with a stream of jobs that finish in order, the whole algorithm runs in O(n).
Why it is optimal: greedy stays ahead
Let the greedy picks be i₁, i₂, …, iₖ in the order chosen. Let an optimal solution sorted by finish time be j₁, j₂, …, jₘ. Write f(x) for the finish time of interval x. We want to show k = m.
Claim: for every r ≤ k, f(iᵣ) ≤ f(jᵣ).
- Base case, r = 1. Greedy picks the interval with the smallest finish time overall, so f(i₁) ≤ f(j₁).
- Inductive step. Assume f(iᵣ₋₁) ≤ f(jᵣ₋₁). Since jᵣ is compatible with jᵣ₋₁, it starts at or after f(jᵣ₋₁), and therefore at or after f(iᵣ₋₁). So jᵣ was still available when greedy chose its r-th interval. Greedy takes the available interval with the earliest finish, so f(iᵣ) ≤ f(jᵣ).
Conclusion. Suppose m > k. Then jₖ₊₁ exists and starts at or after f(jₖ) ≥ f(iₖ). That means jₖ₊₁ was still available after greedy's last pick, and greedy would have taken it. This contradicts greedy stopping at k. So m = k.
The proof uses both properties from earlier chapters. The base case is the greedy choice property: some optimal solution contains the earliest-finishing interval. The inductive step is optimal substructure: once that interval is taken, what remains is the same problem restricted to intervals that start after it ends.
Edge cases and common errors
Closed versus half-open intervals. If your domain treats (1, 4) and (4, 7) as conflicting, as with closed intervals or a required cleanup gap, change the test to start > last_end or to start >= last_end + gap. Getting this wrong is the most common bug in practice. The result is off by one interval, and tests on random data rarely catch it.
Ties in finish time. When several intervals share a finish time, greedy takes one of them, and that interval blocks the rest. It does not matter which one is taken, because every later decision depends only on last_end. You do not need a secondary sort key for correctness. Add one only if you need the output to be the same on every run.
Zero-length intervals. An interval (5, 5) with half-open semantics overlaps nothing. The algorithm takes it if 5 >= last_end, and last_end stays at 5. This is correct, but check that it matches your domain. A zero-minute meeting might be a data error.
Sorting by the wrong key. sorted(intervals) sorts by start time because tuples compare element by element. That gives the earliest-start rule, which is wrong. Always pass key=lambda iv: iv[1].
Empty input. The loop never runs and the function returns [], so no special case is needed.
Variations
| Variation | Still greedy? | What changes |
|---|---|---|
| Maximize count, one resource | Yes | This chapter |
| Maximize count, k identical resources | Yes | Assign each interval to the resource that freed up most recently but still before it starts |
| Use the fewest resources so that every interval fits | Yes | Different problem: interval partitioning, next chapter |
| Maximize total weight | No | Dynamic programming over intervals sorted by finish time |
| Maximize total time covered | No | Equivalent to weighted scheduling with weight = length |
Exercise
Run selectactivities on [(2, 3), (1, 2), (3, 4), (0, 5), (2, 4)]. List the chosen intervals in order and give the final value of lastend.
Show answer
Sorted by finish time: (1,2), (2,3), (2,4), (3,4), (0,5). It takes (1,2) with lastend=2, then takes (2,3) with lastend=3, rejects (2,4) because 2 < 3, takes (3,4) with lastend=4, and rejects (0,5). Result: [(1, 2), (2, 3), (3, 4)], with lastend = 4.
Exercise
A student proposes "pick the interval that starts latest among those that finish earliest." Is any tie-breaking rule needed among intervals with equal finish time for the count to be optimal? Explain using the proof.
Show answer
No. The proof only uses f(ir) ≤ f(jr). Any interval with the minimum available finish time satisfies that inequality, and the next choice depends only on last_end, which is the same whichever tied interval was taken. Tie-breaking can change which intervals appear in the output but never how many.
Exercise
Meetings require a 15-minute cleanup gap after each one, and times are in minutes. Modify select_activities to enforce this and state the result for [(0, 30), (40, 60), (75, 90)].
Show answer
Change the condition to if start >= last_end + 15:. Taking (0,30) gives last_end=30. (40,60) is rejected because 40 < 45. (75,90) is taken because 75 ≥ 45. Result: [(0, 30), (75, 90)]. The change is still optimal because it is the same as extending every interval's end by 15 and running the original algorithm.