What makes an algorithm greedy
A greedy algorithm builds its answer one decision at a time. At each step it takes the option that looks best by some simple rule and never takes it back. There is no search over alternatives and no table of subproblems, which is why greedy algorithms are usually short and fast: often one sort and one linear scan.
The catch is that "looks best now" is not the same as "is best overall". A greedy algorithm is correct only when two things hold:
- Greedy choice property. Some optimal solution contains the greedy first choice. Committing to it never rules out reaching an optimum.
- Optimal substructure. After that choice, what is left is a smaller instance of the same problem, and an optimal answer to it combined with the choice is optimal for the whole.
Dynamic programming needs optimal substructure too. The difference is the first property: DP tries every choice and keeps the best, greedy trusts one. When the greedy choice property fails, the algorithm still runs and still returns something plausible. It is just wrong, so every greedy algorithm needs a proof or a counterexample, never a hunch.
You have already seen greedy algorithms: Dijkstra settles the closest unsettled node, and Kruskal's minimum spanning tree algorithm (built on union-find) adds the cheapest edge that does not close a cycle. Huffman coding, which merges the two least frequent symbols repeatedly, is another. Each comes with its own proof.
Interval scheduling
You have one room and a list of requested bookings, each with a start and an end time. Accept as many as possible so that no two accepted bookings overlap. This is interval scheduling, also called activity selection. Every booking is worth the same; only the count matters.
Endpoints: half-open intervals
Before any algorithm, decide what "overlap" means at the boundary. This lesson, the lab and all four
implementations use half-open intervals [start, end): the interval contains start but not
end. A booking [9, 10) ends exactly when [10, 11) begins, and the two do not conflict. Two
half-open intervals a and b are compatible exactly when
a.end <= b.start or b.end <= a.start
Half-open intervals are the usual convention for time slots, array slices (a[lo:hi] in Python,
[first, last) iterator ranges in C++) and calendar software, because adjacent ranges tile without
gaps or double counting. If your data uses closed intervals [start, end], change >= to > in
the check below; nothing else changes.
Three plausible rules
Which booking should the greedy algorithm accept first?
- The shortest one: it uses the least time.
- The one that starts first: it is the first to need a decision.
- The one that ends first: it frees the room soonest.
Only the third is always optimal. Small counterexamples sink the other two, and the lab has a preset for each:
- Shortest first fails:
[0, 6),[5, 8),[7, 13). The shortest,[5, 8), overlaps both others, so shortest-first accepts one booking. Earliest end accepts[0, 6)and[7, 13): two. - Earliest start fails:
[0, 10),[1, 3),[4, 6),[7, 9). Earliest start takes[0, 10)and blocks everything else. Earliest end takes the three short bookings.
A rule that fails on four intervals fails on millions too; one counterexample is a complete refutation.
The algorithm
sort the intervals by end (ties: earlier start, then input order)
last_end = none
for each interval [s, e) in that order:
if last_end is none or s >= last_end:
take it
last_end = e
else:
skip it # overlaps the last interval taken
The tie-break does not change the number of intervals taken, but it does change which
ones, and a fixed rule is what lets one fixture check the lab and all four languages. In the
Ties and touching ends preset, three intervals end at 5; the one starting at 0 wins, and [5, 6)
still fits afterwards because touching is allowed.
Notice that the scan compares each interval only with last_end, not with every interval taken
so far. That is enough: everything taken ends at or before last_end, and every interval still to
come ends at or after it, so the last one taken is the only one that can conflict.
Why earliest end first is optimal
Claim. Let g₁, g₂, …, gₖ be the intervals the greedy algorithm takes, in order, and let
o₁, o₂, …, oₘ be any compatible set, sorted by end time. Then k ≥ m.
Greedy stays ahead. First show by induction that end(gᵢ) ≤ end(oᵢ) for every i ≤ k.
- For
i = 1:g₁has the smallest end time of all intervals, soend(g₁) ≤ end(o₁). - For
i > 1:oᵢstarts at or afterend(oᵢ₋₁)(theo's are compatible and sorted), and by inductionend(oᵢ₋₁) ≥ end(gᵢ₋₁). Sooᵢwas still available when greedy pickedgᵢ, and greedy picked the available interval with the smallest end:end(gᵢ) ≤ end(oᵢ).
Now suppose m > k. Then oₖ₊₁ exists and starts at or after end(oₖ) ≥ end(gₖ), so it was still
compatible after greedy's last pick, and greedy would have taken it. Contradiction; so k ≥ m.
The exchange view says the same thing differently: take any optimal schedule and replace its
first interval by g₁. Since g₁ ends no later, it conflicts with nothing the old first interval
did not, so the schedule stays valid and the same size. Repeat on the rest. Step by step, any
optimum turns into the greedy schedule without getting smaller. Exchange arguments are the
standard way to prove a greedy choice: show that swapping the greedy choice into an optimal
solution never makes it worse.
Merging intervals
A related sweep answers a different question: given intervals, what does their union look like? For example, which hours of the day is the room booked at all? The answer is a list of disjoint blocks.
sort the intervals by start (ties: earlier end, then input order)
current = first interval
for each next interval [s, e):
if s <= current.end: # overlaps or touches
current.end = max(current.end, e)
else: # a gap: current is finished
emit current
current = [s, e)
emit current
With half-open intervals, [1, 3) and [3, 5) share no point, but their union [1, 5) has no gap,
so the merge joins them (s <= current.end, not <). If you need to keep touching intervals
separate (say, distinct meetings that happen to be back to back), use < instead. The lab and the
implementations merge touching intervals, and the tests compare them with a brute-force reference
that marks every covered time unit and reads off the runs.
Sorting by start is what makes one pass enough: once an interval starts after the current block's
end, every later interval starts even later, so nothing can reach back into the finished block.
Note the max: an interval nested inside the block ([2, 3) inside [1, 10)) must not shrink it.
Complexity
| Step | Time | Extra space |
|---|---|---|
| Sort | O(n log n) | O(n) for the index array or copy (the sort itself may add O(log n) to O(n)) |
| Selection scan | O(n): one comparison per interval | O(k) for the result |
| Merge scan | O(n): one comparison per interval after the first | O(number of blocks) |
The sort dominates: O(n log n) for both problems. If the intervals arrive already sorted, the scan alone is O(n). The Checks metric in the lab counts the scan comparisons only; the sort is shown as one step.
When greedy fails
Coin change with non-canonical coins
Make change for an amount using the fewest coins. Greedy says: always take the largest coin that
fits. With coins {1, 5, 10, 25} that is optimal. With coins {1, 3, 4} and amount 6, greedy
takes 4 + 1 + 1 (three coins), but 3 + 3 uses two. Taking the 4 felt best and was wrong, and
greedy never reconsiders.
Coin systems where greedy is always optimal are called canonical; many real currencies are,
but that is a property to check, not to assume. The general problem is solved by dynamic
programming: best[a] = 1 + min(best[a − c]) over coins c ≤ a. See
From recursion to dynamic programming
for how such tables are built.
Knapsack: fractional yes, 0/1 no
With a capacity and items that have weights and values, the fractional knapsack (you may take part of an item) is solved greedily: sort by value per unit of weight and fill in that order, splitting the last item. An exchange argument proves it. In the 0/1 knapsack (all or nothing) the same rule fails: capacity 10, items (weight 6, value 30), (5, 20), (5, 20). The best ratio is the first item (5 per unit), which leaves room for nothing else: 30. The two others give 40. That problem needs the table in 0/1 knapsack.
Weighted intervals
Give each booking a value and maximise the total value instead of the count, and earliest end
first breaks: [0, 10) worth 100 beats [0, 2) and [3, 5) worth 1 each. Weighted interval
scheduling is a DP: sort by end, and for each interval choose the better of skipping it or taking
it plus the best answer among intervals that end by its start (found with binary search). Still
O(n log n), but it is no longer greedy.
The pattern: greedy works when one local quantity (end time, value density, edge weight) settles the decision for good. When the right choice depends on what comes later, you need to keep options open, and that is dynamic programming's job.
The teaching implementation
IntervalScheduling.Select / select sorts the indices by (end, start, index) and scans;
Merge / merge sorts by (start, end) and sweeps. The listings are the exact files the tests
run. Each language reads one shared fixture (the classic eleven-activity example, both failing
rules, ties on end time, touching and duplicate intervals, nested intervals and empty input), then
checks 500 random instances: the selection must be pairwise compatible and as large as a brute
force over all subsets finds, and the merge must equal the runs of a covered-unit array.
Language notes
| Language | Sorting by several keys | Stability |
|---|---|---|
| C# | Array.Sort / List<T>.Sort with a comparison; value tuples compare element by element, so (a.End, a.Start, i).CompareTo(...) is a one-line multi-key comparison. |
Array.Sort and List<T>.Sort are unstable (introsort). LINQ OrderBy(...).ThenBy(...) is stable but allocates a new sequence. |
| Python | sorted(items, key=lambda i: (end, start, i)); tuples compare lexicographically. |
sorted and list.sort are stable (Timsort), so sorting by one key keeps earlier order on ties. |
| Java | Comparator.comparingInt(...).thenComparingInt(...). With boxed indices, write Comparator.<Integer>comparingInt(...) so the lambda types infer. A record gives a tidy interval type with equals for free. |
List.sort and Collections.sort on objects are stable; Arrays.sort on primitive arrays is not (it does not matter for primitives). |
| C++ | A lambda comparing std::tuple(...) or std::tie(...); with C++20 ranges, std::ranges::sort(v, {}, &Interval::end) sorts by one projected key. |
std::sort is not stable; std::stable_sort is. Comparators must be a strict weak ordering (<, never <=). |
Adding the input index as the last key makes every comparison total, so stability stops mattering: the order is fully determined in all four languages. Without it, two intervals with the same start and end could come out in either order from an unstable sort; for merging that is harmless (they are indistinguishable), for selection it changes which index is reported.
Common mistakes
- Sorting by start for selection. That is the earliest-start rule, which fails.
- Using
>instead of>=with half-open intervals (or the reverse with closed ones): back-to-back bookings are wrongly rejected or wrongly accepted. - Comparing with every taken interval instead of just the last end. Correct, but O(n·k).
- Forgetting
maxin the merge, so a nested interval shrinks the block. - Trusting a greedy rule because it worked on the examples. Try to break it with three or four intervals first; if you cannot, prove it.
Edge cases
- No intervals: the schedule and the union are empty.
- One interval: it is taken, and it is the only block.
- Identical intervals: selection takes one (the smallest index); merge emits it once.
- All intervals overlap one point: selection takes exactly one.
- Intervals that only touch: all are taken, and they merge into one block.
Worked practice
1. Run earliest end first on [1, 4), [3, 5), [0, 6), [5, 7), [3, 9), [5, 9), [6, 10),
[8, 11), [8, 12), [2, 14), [12, 16). Which intervals are taken?
Answer
[1, 4), [5, 7), [8, 11), [12, 16): four. After [1, 4) the last end is 4, so [3, 5) and
[0, 6) are skipped; [5, 7) fits; [3, 9), [5, 9) and [6, 10) start before 7; [8, 11) fits;
[8, 12) and [2, 14) start before 11; [12, 16) fits. This is the Eleven activities preset.
2. Does "fewest conflicts first" (take the interval that overlaps the fewest others) always work?
Answer
No. It survives the small cases above, but larger counterexamples exist: Kleinberg and Tardos (Algorithm Design, chapter 4) give one with eleven intervals, where the interval with the fewest conflicts blocks two intervals that every optimal schedule needs. A rule being "smart" is not a proof. Earliest end first has a proof.
3. Merge [8, 10), [1, 3), [2, 6), [15, 18), [3, 5), [16, 17).
Answer
Sorted by start: [1, 3), [2, 6), [3, 5), [8, 10), [15, 18), [16, 17). Blocks: [1, 6)
([3, 5) is inside it), [8, 10), [15, 18) ([16, 17) is nested).
4. Coins {1, 6, 10}, amount 12. What does greedy return, and what is optimal?
Answer
Greedy takes 10, then 1 and 1: three coins. Two 6s make two coins. {1, 6, 10} is not a canonical
system; use the DP.
5. How many rooms are needed so that every booking can be accepted?
Answer
The maximum number of intervals that overlap at one moment. Sort all endpoints (with an end at time
t before a start at time t, because the intervals are half-open), sweep while counting
+1 at each start and −1 at each end, and take the maximum. O(n log n). Assigning bookings to
rooms greedily, each to any room that is free, uses exactly that many.
Summary
- A greedy algorithm makes one irrevocable choice per step; it is correct only with a proof (greedy choice + optimal substructure), and wrong rules are refuted by a single counterexample.
- Interval scheduling: sort by end time and take every interval that starts at or after the last end. Optimal by "greedy stays ahead" or an exchange argument. O(n log n).
- Merging: sort by start and extend the current block while the next start is at most its end. Decide explicitly whether touching intervals merge. O(n log n).
- Shortest first and earliest start first fail; so does greedy coin change with non-canonical coins, 0/1 knapsack by value density and weighted interval scheduling: those need DP.