GreedyAlgorithmaka earliest finish first, maximum non-overlapping activities

Activity Selection

Pick the maximum number of mutually compatible activities by repeatedly taking the one that finishes earliest.

▶ VisualizePattern: GreedyPractice (3)
Progress
Before this, know:Array

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.

greedyintervalsexchange argumentearliest finishsorting

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

  1. Sort activities by finish time (ties: any order).
  2. Select the first activity; set lastFinish to its finish time.
  3. Scan the rest in order: if start ≥ lastFinish, select it and update lastFinish; otherwise skip.
  4. 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.

A
A
A
B
B
B
B
B
B
B
B
B
B
B
C
C
C
D
D
E
E
E
F
F
F
Activities (grid order)
idstartendstate
A14—
B011—
C47—
D68—
E710—
F1114—
1/186 activities compete for one room, drawn on a shared time axis: each row is one activity and its filled cells are the time units it occupies. Two activities clash exactly when their rows overlap vertically, and we want the largest set with no vertical overlap at all.
Interval under considerationTaken / keptRejected — it conflictsAlready decided
1sort activities by finish time, earliest first
2last = -infinity # finish time of the most recent activity taken
3for (s, f) in sorted order:
4 if s >= last: # compatible with everything taken so far
5 take it; last = f
6 else:
7 skip it # it overlaps the activity we already hold
8return the taken activities
Variables
activities6
horizon14
Complexity
best O(n)
avg O(n log n)
worst O(n log n)
space O(1)
Speed

Pseudocode

1sort activities by finish
2chosen = [a[0]]; lastFinish = a[0].finish
3for act in a[1:]:
4 if act.start >= lastFinish:
5 chosen.push(act); lastFinish = act.finish
6return chosen

Implementations

1from typing import NamedTuple
2
3# Activity selection: given intervals, choose the largest set that do not
4# overlap. The greedy is "always take the activity that FINISHES earliest
5# 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: int
12 finish: int
13
14
151 · Sort by finish time; that single ordering is the whole algorithm
16def 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 finish
20 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].finish
26 return chosen
27
28
293 · Count only — the same sweep without recording indices
30def max_activities(acts: list[Activity]) -> int:
31 count = 0
32 last_finish = float("-inf")
33 for a in sorted(acts, key=lambda x: x.finish):
34 if a.start >= last_finish:
35 count += 1
36 last_finish = a.finish
37 return count
38
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 = 0
45 last_finish = float("-inf")
46 for a in sorted(acts, key=lambda x: x.start):
47 if a.start >= last_finish:
48 count += 1
49 last_finish = a.finish
50 return count # NOT optimal — included to show the failure
51
52
535 · The exchange argument: if an optimal solution's first activity finishes
54# later than the greedy's, swapping in the greedy one keeps every later choice
55# 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.start
Walkthrough
  1. sorted(range(len(acts)), key=lambda i: acts[i].finish) produces the index permutation in one expression.
  2. Activity(NamedTuple) gives an immutable record with named fields, __eq__ and __repr__ for three lines.
  3. float("-inf") is the initial sentinel; because Activity fields are ints, the comparison is int-to-float, which Python handles exactly for any realistic magnitude. The start < finish precondition is not enforced — a __post_init__ check on a dataclass would catch it, which NamedTuple cannot do.
  4. sorted(acts, key=...) returns a new list, so the counting variants never mutate the caller's data.
  5. Both the correct and the incorrect key are present, differing by one word — which is exactly how close the mistake is in practice.
Complexity (this implementation)
time O(n log n) · space O(n)
Language notes
  • 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 Activity is a NamedTuple, sorted(acts) without a key would order by (start, finish) — plausible-looking and wrong.
  • math.inf and float("-inf") are the same value; the latter reads more explicitly at a single use site.
Common mistakes in this language
  • Calling sorted(acts) with no key and getting start-time order by accident, since NamedTuple compares 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.
Language differences that matter here
  • Sort stability differs: Python and JS/TS sorts are stable, so ties in finish time keep input order; C++ std::sort is not, and the chosen indices can vary between runs.
  • A NamedTuple in Python compares field-by-field, so sorted(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

Best
O(n)
Average
O(n log n)
Worst
O(n log n)
Space
O(1)

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

Use it when
  • 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.
Avoid it when
  • Weighted intervals: activities A=[0,10] weight 10, B=[0,3] weight 1, C=[4,10] weight 1. Earliest-finish picks B then C for total 2; the optimum is A alone 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 > lastFinish when 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.
Mock interviews

Example problems

Check yourself

Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.

  1. A problem looks like it could be greedy. How do you decide whether greedy is correct or whether you need DP?

    Show a strong 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 amount 6 — greedy gives 4+1+1, optimum is 3+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 →
  2. You have written an algorithm. How do you convince me it is correct without running it on every input?

    Show a strong 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 when lo > hi the range is empty so the target is absent. For Two Pointers (Opposite Ends): "every solution pair lies within [l, r]". For Kadane's Algorithm: "cur is the maximum sum of a subarray ending at i". 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 assuming dp[j] is correct for all j it 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 < 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.

    Full interview question, with follow-ups and red flags →
  3. Prove earliest-finish-first is optimal for interval scheduling.

    Show a strong answer

    Let O be optimal with first interval o_1; greedy picks g_1 with end(g_1) ≤ end(o_1). Replacing o_1 by g_1 keeps O feasible and the same size. Induct on the remainder after end(g_1).

    Full interview question, with follow-ups and red flags →