Activity Selection
Pick the maximum number of mutually compatible activities by repeatedly taking the one that finishes earliest.
You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.
Overview
Given n activities with start and finish times, choose the largest set such that no two overlap. The greedy rule is earliest finish time first: sort by finish, take the first activity, then repeatedly take the next activity whose start is at or after the finish of the last one taken.
This is the textbook example of the greedy-choice property: a locally optimal choice (finish as early as possible, leaving the most room) is part of some globally optimal solution, and after making it the remaining problem has the same form. It is the unweighted special case of Interval Scheduling; the weighted version needs Dynamic Programming.
Intuition
A mental model before the formal terms.
You want to attend as many talks as possible in one room. The talk that ends soonest frees you up earliest, so whatever you could have attended after any other first choice, you can still attend after this one. Ending early never costs you anything.
Sorting by start time or by duration feels natural but fails: a talk that starts first may run all day, and the shortest talk may sit in the middle and block two long ones on either side.
How it works
- Sort activities by finish time (ties: any order).
- Select the first activity; set
lastFinishto its finish time. - Scan the rest in order: if
start ≥ lastFinish, select it and updatelastFinish; otherwise skip. - The selected list is a maximum-size compatible set.
Why it works
Exchange argument. Let a₁ be the activity with the earliest finish and let OPT be any optimal solution. OPT's first activity o₁ (in finish order) finishes no earlier than a₁, so replacing o₁ by a₁ keeps the set compatible (everything after o₁ starts at or after f(o₁) ≥ f(a₁)) and the same size. Hence some optimal solution begins with a₁.
Optimal substructure. After choosing a₁, the remaining activities compatible with it form an instance of the same problem, and an optimal solution to the original is a₁ plus an optimal solution to the remainder. Induction on n completes the proof.
Sorting by finish time is what makes "compatible with a₁" equal to "starts at or after f(a₁)", which the single scan checks in O(1) per activity.
Recognition
How to tell a problem wants this.
- "Maximum number of non-overlapping intervals / meetings / tasks" with one resource.
- "Minimum number of intervals to remove so the rest do not overlap" — the complement of this problem.
- Unit weights: every interval counts equally. If intervals have values, greedy breaks and you need DP.
Interactive visualization
Play, step, change the input. ← → and space work too.
| id | start | end | state |
|---|---|---|---|
| A | 1 | 4 | — |
| B | 0 | 11 | — |
| C | 4 | 7 | — |
| D | 6 | 8 | — |
| E | 7 | 10 | — |
| F | 11 | 14 | — |
1sort activities by finish time, earliest first2last = -infinity # finish time of the most recent activity taken3for (s, f) in sorted order:4 if s >= last: # compatible with everything taken so far5 take it; last = f6 else:7 skip it # it overlaps the activity we already hold8return the taken activitiesPseudocode
1sort activities by finish2chosen = [a[0]]; lastFinish = a[0].finish3for act in a[1:]:4 if act.start >= lastFinish:5 chosen.push(act); lastFinish = act.finish6return chosenImplementations
1from typing import NamedTuple2 3# Activity selection: given intervals, choose the largest set that do not4# overlap. The greedy is "always take the activity that FINISHES earliest5# among those still compatible" — earliest finish leaves the most room.6# PRECONDITION: every activity has positive duration (start < finish).7# Zero-length activities break the optimality proof — see the walkthrough.8 9 10class Activity(NamedTuple):11 start: int12 finish: int13 14 151 · Sort by finish time; that single ordering is the whole algorithm16def select_activities(acts: list[Activity]) -> list[int]:17 idx = sorted(range(len(acts)), key=lambda i: acts[i].finish)18 192 · Sweep: take an activity whenever it starts at or after the last finish20 chosen: list[int] = []21 last_finish = float("-inf")22 for i in idx:23 if acts[i].start >= last_finish:24 chosen.append(i)25 last_finish = acts[i].finish26 return chosen27 28 293 · Count only — the same sweep without recording indices30def max_activities(acts: list[Activity]) -> int:31 count = 032 last_finish = float("-inf")33 for a in sorted(acts, key=lambda x: x.finish):34 if a.start >= last_finish:35 count += 136 last_finish = a.finish37 return count38 39 404 · Why earliest-finish and not earliest-start or shortest-duration:41# sorting by START fails on [0,10],[1,2],[3,4] (takes 1, optimum is 2)42# sorting by DURATION fails on [0,5],[4,6],[5,10] (takes 1, optimum is 2)43def max_activities_by_start(acts: list[Activity]) -> int:44 count = 045 last_finish = float("-inf")46 for a in sorted(acts, key=lambda x: x.start):47 if a.start >= last_finish:48 count += 149 last_finish = a.finish50 return count # NOT optimal — included to show the failure51 52 535 · The exchange argument: if an optimal solution's first activity finishes54# later than the greedy's, swapping in the greedy one keeps every later choice55# valid (it frees at least as much room) and keeps the count the same.56def compatible(a: Activity, b: Activity) -> bool:57 return a.finish <= b.start or b.finish <= a.startsorted(range(len(acts)), key=lambda i: acts[i].finish)produces the index permutation in one expression.Activity(NamedTuple)gives an immutable record with named fields,__eq__and__repr__for three lines.float("-inf")is the initial sentinel; becauseActivityfields are ints, the comparison is int-to-float, which Python handles exactly for any realistic magnitude. Thestart < finishprecondition is not enforced — a__post_init__check on a dataclass would catch it, whichNamedTuplecannot do.sorted(acts, key=...)returns a new list, so the counting variants never mutate the caller's data.- Both the correct and the incorrect key are present, differing by one word — which is exactly how close the mistake is in practice.
sorted(key=...)computes the key once per element and is stable, so ties keep input order.operator.attrgetter("finish")is a marginally faster key than a lambda for large inputs.- Because
Activityis aNamedTuple,sorted(acts)without a key would order by(start, finish)— plausible-looking and wrong. math.infandfloat("-inf")are the same value; the latter reads more explicitly at a single use site.
- Calling
sorted(acts)with no key and getting start-time order by accident, sinceNamedTuplecompares field by field. - Sorting by start or by duration.
- Using
acts.sort()and mutating the caller's list. - Feeding in zero-length activities, which violate the precondition and make the greedy silently non-optimal.
- Sort stability differs: Python and JS/TS sorts are stable, so ties in finish time keep input order; C++
std::sortis not, and the chosen indices can vary between runs. - A
NamedTuplein Python compares field-by-field, sosorted(acts)silently sorts by start — a trap the C++ struct and the TypeScript interface do not have, because neither is ordered by default. - Index-permutation sorting is the same idiom everywhere, but only Python expresses it in one line (
sorted(range(n), key=...)). - JavaScript again needs an explicit comparator even when sorting plain integer indices, or it orders them lexicographically.
Complexity
Dominated by sorting; O(n) if input is already sorted by finish time. Output list excluded from space.
Compare growth rates in the Complexity Explorer →When to use — and when not to
- Maximizing the count of compatible intervals on a single resource.
- Minimum removals to make intervals non-overlapping (answer =
n − maxCompatible). - As the first pass before a weighted or multi-resource generalization.
- Weighted intervals: activities
A=[0,10] weight 10,B=[0,3] weight 1,C=[4,10] weight 1. Earliest-finish picksBthenCfor total 2; the optimum isAalone with 10. Use weighted Interval Scheduling DP. - Multiple rooms (minimum number of resources to host all activities) — that is Merge Intervals-style sweep or a Priority Queue of end times (Meeting Rooms II), not selection.
- Sorting by start time or shortest duration:
[1,100],[2,3],[4,5]— start-first takes the long one and gets 1; earliest-finish gets 2.
Alternatives
Common mistakes
- Sorting by start time instead of finish time.
- Using
start > lastFinishwhen touching endpoints are allowed (or vice versa) — read the problem's definition of overlap. - Forgetting to sort at all and greedily scanning input order.
- Applying the rule to weighted instances.
Interview patterns
- Non-overlapping Intervals (LeetCode 435): count kept intervals with earliest-finish, return
n − kept. - Minimum Number of Arrows to Burst Balloons: same greedy, counting groups.
- Maximum Length of Pair Chain: earliest-finish on pairs.
- Merge IntervalsIntermediate
Example problems
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
A problem looks like it could be greedy. How do you decide whether greedy is correct or whether you need DP?
Show a strong answerHide the answer
Greedy is correct only if the problem has the greedy-choice property: some locally optimal choice is guaranteed to be part of *some* globally optimal solution, and after making it the remaining problem is a smaller instance of the same kind. Both greedy and DP need optimal substructure; the difference is that DP considers every choice at each state and greedy commits to one. So the question is really: can I prove that one specific choice is always safe?
The tool for that proof is the exchange argument: take any optimal solution that does not make the greedy choice, swap in the greedy choice, and show the result is no worse. In Interval Scheduling, picking the interval that ends earliest is safe because any optimal solution's first interval can be replaced by the earliest-ending one without breaking compatibility with the rest. If the exchange argument does not go through, greedy is suspect. The other tool is counterexample hunting: try small adversarial inputs. Coin Change with coins
{1, 3, 4}and amount6— greedy gives4+1+1, optimum is3+3. That one example kills the greedy for arbitrary denominations, though it works for canonical systems like US coins.A strong candidate knows the sibling pairs: Fractional Knapsack is greedy by value density, 0/1 Knapsack is not (density greedy fails when a low-density item fills the capacity exactly); Activity Selection greedy by earliest finish works, weighted interval scheduling needs DP; minimum spanning tree greedy (Kruskal's Algorithm) works because of the cut property, shortest path with negative edges does not. When unsure in an interview, they say so, write the DP (always correct if the state is right), and note that a greedy would be an optimization to prove later — that ordering is the mark of an engineer who values correctness over cleverness.
Full interview question, with follow-ups and red flags →You have written an algorithm. How do you convince me it is correct without running it on every input?
Show a strong answerHide the answer
Testing shows the algorithm works on the inputs tried; a proof shows it works on all of them. A strong candidate matches proof technique to code shape. Loops → invariants. State a property that holds before the first iteration, is preserved by each iteration, and at termination implies the result. For Binary Search: "the target, if present, lies in
[lo, hi]" — true initially, preserved by each discard because of sortedness, and whenlo > hithe range is empty so the target is absent. For Two Pointers (Opposite Ends): "every solution pair lies within[l, r]". For Kadane's Algorithm: "curis the maximum sum of a subarray ending ati". An invariant that cannot be stated precisely is a signal the algorithm might be wrong.Recursion and DP → induction. Assume the recursive calls return correct answers for smaller inputs and show the combination is correct; the base case anchors it. For DP, the induction is over the topological order of states: "
dp[i]is correct assumingdp[j]is correct for alljit depends on". Greedy → exchange argument. Show any optimal solution can be transformed into the greedy one without losing optimality; if the exchange cannot be made, look for the counterexample that the failed exchange suggests. Graph algorithms → structural lemmas. BFS layers equal distances by induction on distance; Dijkstra's correctness rests on the lemma that the minimum tentative node has its final distance, which holds only with non-negative weights.They also use reduction: "this is exactly interval scheduling, whose greedy is known optimal", which transfers a known proof. And they complement the proof with disciplined edge-case enumeration — empty input, single element, all equal, extreme values, the boundary of every
Full interview question, with follow-ups and red flags →<vs<=— because a proof covers the algorithm while edge cases catch the gap between the algorithm and the code. Finally, they say what they are *not* sure of: "I believe the invariant holds when duplicates are present, let me check the<=branch." That honesty is itself evidence of correctness-oriented thinking.Prove earliest-finish-first is optimal for interval scheduling.
Show a strong answerHide the answer
Let
Full interview question, with follow-ups and red flags →Obe optimal with first intervalo_1; greedy picksg_1withend(g_1) ≤ end(o_1). Replacingo_1byg_1keepsOfeasible and the same size. Induct on the remainder afterend(g_1).