A greedy algorithm takes the choice that looks best now and never takes it back. On these 11 talk requests, booking the talk that ends first fits 5 talks. Booking the one that starts first fits only 3.
Pick a rule and watch it book the hall. Then we build, piece by piece: the scan, the proof that it is safe, where greedy breaks, Huffman codes, coins, matroids and graphs.
You need sorting, a little Python, and the idea of dynamic programming (CLRS Chapter 15). We build the rest from zero.
Based on Chapter 16 of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. It follows Chapter 15, Dynamic Programming. The explanations, toys and devices are our own.
Eleven made-up requests. The best possible count, 5, comes from checking all 2,048 subsets. Ties go to the earlier start.
Chapter 0
Try three tempting rules on small inputs and watch each one lose
You run one lecture hall. Eleven speakers ask for it on the same day, each for a fixed time. Two talks that overlap cannot both happen. You want to book as many talks as you can.
This is the activity selection problem: from a set of time intervals, choose the largest set where no two overlap. Activity i runs from its start si up to its finish fi. The finish moment itself is free, so a talk can start the moment another ends.
A greedy algorithm builds its answer one choice at a time. It takes the choice that looks best now and never takes it back. The hard part is the rule for "best".
Each trap is a small day built to beat one rule. Pick a trap, then switch between the tempting rule and earliest finish.
Made-up days. On the fewest-conflicts trap, the small number at the right of each bar is how many other talks it overlaps.
| Rule | Its trap | Rule books | Best |
|---|---|---|---|
| Shortest first | [0, 5), [4, 7), [6, 11) | 1 | 2 |
| Earliest start | [0, 10), [1, 3), [4, 6), [7, 9) | 1 | 3 |
| Fewest conflicts | 11 talks in the device | 3 | 4 |
The rule that works: book the talk that finishes first. Then repeat on the talks that start after it ends. It uses up the least of the day, so it leaves the most time for the rest.
A worked number, on the first trap. The short talk [4, 7) overlaps both others, so shortest first books 1 talk. Earliest finish takes [0, 5), then [6, 11): 2 talks.
The failure. Symptom: a scheduler passes your hand tests but books fewer talks on real days. Measure: on random days of up to 15 talks, compare it with brute force over all subsets. Fix: change the rule. One counterexample is enough to reject a greedy rule.
Chapter 1
Step the earliest-finish scan and watch one clock decide every talk
Earliest finish turns into a short program. Sort the activities by finish time. Walk the list once. Keep each activity that starts at or after the finish of the last one you kept.
One test decides each activity. Call the activity you look at am, with start sm. Call the last activity you kept ak, with finish fk.
s-m is at least f-k.
If the new activity starts no earlier than f-k, keep it and move f-k to its finish. If it starts earlier, skip it. f-k only moves forward.
The last kept activity A finishes at 4, so f-k = 4. D starts at 5: 5 is at least 4, so keep D and set f-k = 7. E starts at 3: 3 is less than 7, so skip E.
The rows run in finish order. Press Step. The warm line is last_finish; blue is the activity under test.
These are the eleven activities CLRS uses in Section 16.1, named A to K in finish order.
The worked number. The scan keeps A [1, 4), D [5, 7), H [8, 11) and K [12, 16). A brute-force search over all 2,048 subsets finds no set of 5, and four different sets of 4. Greedy finds one of them with 11 tests.
The cost is the sort, about n log n steps, plus n tests. For 50 activities, brute force would check 250 subsets, about 1.1 × 1015.
The failure. Symptom: a talk that ends at 4 and a talk that starts at 4 are never booked together. Measure: print the test. Fix: use "at least" (≥), not "greater than". The intervals are half-open, so touching is not overlapping.
Chapter 2
Swap the greedy choice into any best answer and see that nothing breaks
Picking the earliest finisher now might seem to block a better plan later. The exchange argument shows it never does. Take any best answer. Swap the greedy choice into it. Show the swap keeps it legal and no worse.
Two facts make a greedy algorithm correct:
Name the pieces. Let O be any largest set of compatible activities. Let ak be the activity in O that finishes first. Let a1 be the activity that finishes first of all: the greedy choice.
O-prime equals O without a-k, together with a-1.
Remove a-k from O and put a-1 in its place. O-prime has the same size as O. It has no overlap: a-1 finishes no later than a-k, and every other activity in O starts after a-k finishes.
O = {B, D, I, K} is optimal. Its first finisher a-k is B [3, 5). The greedy choice a-1 is A [1, 4). The next activity in O, D, starts at 5, and A ends at 4. So O-prime = {A, D, I, K}: still 4 activities, still no overlap.
The top track is greedy's set. The bottom track is an optimal set O. Press Swap to replace the first activity where they differ.
The same eleven CLRS activities as Chapter 1. These three sets and greedy's A D H K are the only optimal sets.
Then repeat on the rest. After a1, the activities that start at f1 or later form a smaller copy of the problem. Induction on the number of picks finishes the proof: every greedy pick is safe.
The failure. Symptom: you trust a rule because it worked on five examples. Measure: try to write the swap. Which element of O do you replace, and why is the result legal and no worse? Fix: if no swap works, hunt for a counterexample, like the traps of Chapter 0.
Chapter 3
Fill one bag two ways and see the same rule win once and lose once
A thief has a bag that holds 50 kg. Three items are in the room. The greedy rule: take the item with the most value per kilogram first.
| Item | Weight | Value | Value per kg |
|---|---|---|---|
| A | 10 kg | $60 | $6 |
| B | 20 kg | $100 | $5 |
| C | 30 kg | $120 | $4 |
There are two versions. In the fractional knapsack, you may take part of an item, like gold dust. In the 0/1 knapsack, you take a whole item or none, like gold bars.
Each row is the bag. Slide the capacity. Teal is what greedy takes, pale teal a part of an item, purple the best whole-item choice.
The items are the CLRS example of Section 16.2. The page finds the best 0/1 choice by checking all 8 subsets.
The worked number at 50 kg. Fractional greedy takes all of A ($60, 40 kg left), all of B ($100, 20 kg left), then 20 of C's 30 kg: $120 × 20/30 = $80. Total $240, and the bag is full. The 0/1 greedy takes A and B for $160 and leaves 20 kg empty, because C does not fit. The best whole-item choice is B and C: $220.
Why the difference? In the fractional case the exchange argument works one kilogram at a time. Any kilogram of a cheaper item can swap for a kilogram of a richer one. Whole items cannot swap a kilogram at a time.
The 0/1 version needs dynamic programming. Let K[i][w] be the best value using only the first i items in a bag of capacity w. Item i weighs wi and is worth vi.
K of i and w equals the larger of K of i minus 1 and w, and v-i plus K of i minus 1 and w minus w-i.
For item i, try both choices. Leave it, and the answer is K[i−1][w]. Take it, and you gain v-i but have only w − w-i kg for the first i − 1 items. Keep the larger.
With items A, B, C and w = 50: K[2][50] = 160 (A and B) and K[2][20] = 100 (B). So K[3][50] = max(160, 120 + 100) = 220.
The table has n × W cells, so the work is about n times W. That is pseudo-polynomial: polynomial in the number W, but not in the number of digits needed to write W.
The failure. Symptom: a packing tool leaves space empty and misses a better set. Measure: run the DP on the same items and compare. Fix: if items cannot be split, use the DP. Keep greedy only for items that can be split.
Chapter 4
Build the code tree from the bottom up and count the bits it saves
A file holds 100,000 letters from an alphabet of six. A fixed code gives each letter 3 bits: 300,000 bits. But a appears 45,000 times and f only 5,000. Give a a short codeword and f a long one, and the file shrinks.
A prefix code gives no letter a codeword that begins another letter's codeword. Then a decoder reads bits left to right and always knows where a letter ends. Every prefix code is a binary tree: letters sit at the leaves, a left edge is 0, a right edge is 1.
Huffman's algorithm (David Huffman, 1952) builds the best such tree:
Press Step to merge the two rarest nodes. Blue marks the pair taken out; teal nodes are merges. When one tree is left, the codes appear.
The six-letter set is the CLRS example of Section 16.3, in thousands. Ties go to the node made first, so other valid trees exist with the same cost.
How good is a tree? Call the frequency of letter c c.freq. Call its depth in tree T, which is its codeword length, dT(c). The cost B(T) is the number of bits for the whole file.
B of T equals the sum over letters c of c-freq times d-T of c.
For each letter, multiply c-freq by the length of its codeword. Add these products. Frequent letters near the root keep B(T) small.
abracadabra has a 5, b 2, r 2, c 1, d 1. The tree gives a 1 bit and the others 3 bits. B(T) = 5 × 1 + 2 × 3 + 2 × 3 + 1 × 3 + 1 × 3 = 23 bits. A fixed 3-bit code needs 11 × 3 = 33 bits.
A shortcut: B(T) also equals the sum of every merged frequency, 2 + 4 + 6 + 11 = 23. Each merge adds one bit to every letter under it. For the CLRS six letters, B(T) is 224,000 bits against 300,000.
The cost of the build: n − 1 merges, each with a few heap operations of about log n steps. Total about n log n for an alphabet of n letters.
The failure. Symptom: the decoder outputs garbage after the first letter. Measure: check whether any codeword is the start of another. Fix: put letters only at leaves, and read every code off the tree.
Chapter 5
Prove the merge is safe, then measure the gap to the floor no code can beat
The proof has the same two parts as Chapter 2.
The second part rests on one count. Let T be a tree for the full alphabet with x and y as sibling leaves. Let T′ be the same tree with that pair replaced by the single leaf z.
B of T equals B of T-prime plus x-freq plus y-freq.
x and y sit one level below where z sits. So each of their x-freq + y-freq appearances costs one more bit. Nothing else changes. A cheaper T-prime would give a cheaper T, so a best T-prime gives a best T.
In abracadabra, merge c and d into z with frequency 2. The best tree for a 5, b 2, r 2, z 2 costs 21 bits. Add 1 + 1 and get 23 bits, the Huffman cost.
How low can any code go? Claude Shannon's entropy is the floor. Let pc be the probability of letter c: its count divided by the total.
H equals minus the sum over c of p-c times log base 2 of p-c.
Give each letter its ideal length, log base 2 of 1 over p-c. Weight each length by p-c and add. No prefix code averages fewer bits than H. Huffman's average L is always less than H + 1.
abracadabra: H = 0.455 × 1.14 + 2 × 0.182 × 2.46 + 2 × 0.091 × 3.46 = 2.04 bits per letter. Huffman's L = 23 / 11 = 2.09. The gap is 0.05 bits.
Four letters. Slide how common a is; b, c and d share the rest in the ratio 2 : 1 : 1. Watch Huffman's average L stay between H and H + 1.
Made-up probabilities. The page runs Huffman's algorithm live for each setting.
At 50% the probabilities are 1/2, 1/4, 1/8 and 1/8. Each ideal length is a whole number, so L = H = 1.75 bits. Push a to 95% and H falls to 0.36 bits, but a still needs 1 whole bit, so L is 1.075 bits.
The failure. Symptom: Huffman barely shrinks a file where one letter is 95% of the text. Measure: compare L with H. For two letters at 95% and 5%, H = 0.29 bits but L = 1 bit. Fix: code blocks of letters together, or use arithmetic coding, which is not limited to whole bits per letter.
Chapter 6
Pick a coin set and an amount, and find every amount where greedy pays too many coins
Make change for an amount with the fewest coins. The cashier's rule is greedy: take the largest coin that fits, then repeat on what is left.
Choose a coin set and slide the amount. The strip below shows every amount from 1 to 40; red cells are amounts where greedy uses more coins than needed.
The fewest coins come from the dynamic program below, run live. We made up the coin sets other than US coins.
With US coins 25, 10, 5 and 1, the strip has no red cell. With 4, 3 and 1, the rule fails at 6: greedy pays 4 + 1 + 1, three coins, but 3 + 3 is two.
The greedy-choice property fails here. No swap turns the best answer {3, 3} into an answer that contains a 4. A coin set where greedy is always right is called canonical. US coins are canonical; 4, 3, 1 is not. You check this. You do not guess it.
The fix is a dynamic program. Let C[a] be the fewest coins that make amount a, with C[0] = 0. Let c stand for one coin value.
C of a equals 1 plus the minimum, over coins c no larger than a, of C of a minus c.
Try each coin c as the last coin. It costs 1, plus the best way to make a − c. Keep the cheapest. Fill C from 0 upward, so every C[a − c] is ready when you need it.
Coins 4, 3, 1: C[2] = 2, C[3] = 1, C[5] = 2. So C[6] = 1 + min(C[2], C[3], C[5]) = 1 + min(2, 1, 2) = 2. The winning last coin is 3.
The failure. Symptom: a change machine gives three coins where two would do. Measure: run greedy and the DP for every amount up to a few hundred and list where they differ. Fix: use the DP, which costs the amount times the number of coin values.
Chapter 7
Schedule seven tasks by penalty and see the structure that makes greedy exact
Seven tasks each take one hour on one machine. Each task has a deadline and a penalty you pay if it finishes late. Which tasks should run on time?
The greedy rule: take tasks in order of penalty, highest first. Keep a task if all kept tasks can still finish on time. Put it in the latest free hour at or before its deadline.
Press Step. The top row is hours 1 to 7. Each task tries its deadline hour, then earlier hours. A task with no free hour is late.
The tasks are the CLRS example of Section 16.5: deadlines 4, 2, 4, 3, 1, 4, 6 and penalties 70, 60, 50, 40, 30, 20, 10.
How do we know a set can finish on time? For a set A of tasks, let Nt(A) be the number of tasks in A with deadline t or earlier.
N-t of A is at most t, for every t from 1 to n.
By hour t, only t one-hour tasks can finish. So the tasks due by t must number at most t. If this holds for every t, run the set in deadline order and every task is on time.
The kept set {a1, a2, a3, a4, a7} has deadlines 4, 2, 4, 3, 6. N-2 = 1, N-3 = 2, N-4 = 4, N-6 = 5: all fine. Add a5 (deadline 1) and N-4 = 5, more than 4. So a5 is late. The late tasks are a5 and a6: penalty 30 + 20 = 50.
Why is greedy exact here? The on-time sets form a matroid: a family of "independent" sets with two rules.
CLRS proves that on any matroid with weights, greedy by weight finds a heaviest independent set. The forests of a graph form a matroid too, which is why Kruskal's algorithm works (Chapter 8).
The 0/1 knapsack is not a matroid. Take a 10 kg bag. A = {one 10 kg item} and B = {two 5 kg items}. B is larger, but neither of its items fits next to A. The exchange rule fails.
The failure. Symptom: scheduling by earliest deadline lets a big penalty go late. Measure: compare the total penalty with a brute-force search on small cases. Fix: order by penalty and test each set with Nt.
Chapter 8
Step Kruskal's algorithm and see the same exchange idea in later chapters
A town wants to link six buildings with cable. Each possible link has a cost. Every building must be reachable, and the total cost must be as low as possible.
That is a minimum spanning tree: edges that connect every node of a weighted graph, with no cycle and the least total weight. Kruskal's algorithm sorts the edges by weight. It keeps each edge that does not close a cycle.
Press Step to test the next lightest edge. Teal marks a kept edge. A grey dashed edge would close a cycle, so Kruskal skips it.
A made-up graph with nine edges of distinct weights 1 to 9.
The worked number. Kruskal keeps DE (1), CF (2), BE (3), AB (4) and BC (5). Five edges join six nodes, so the tree is complete, with total weight 15. AD (6) would close the cycle A, B, E, D, so Kruskal skips it.
The exchange argument here is the cut property. Split the nodes into two groups. The lightest edge between the groups belongs to some minimum spanning tree. If a tree left it out, adding it makes a cycle that crosses the split twice. Drop the other crossing edge, which is no lighter, and the tree gets no heavier.
| Problem | Greedy rule | Exact? | CLRS chapter |
|---|---|---|---|
| Minimum spanning tree | Lightest edge that closes no cycle (Kruskal) | Yes, by the cut property | 23 |
| Shortest paths | Finish the closest unfinished node (Dijkstra) | Yes, if no edge weight is negative | 24 |
| Set cover | Pick the set that covers the most uncovered items | No; at most about ln n + 1 times the best | 35 |
The failure. Symptom: Dijkstra returns a wrong distance. Take edges S→A 2, S→B 3 and B→A −2. Dijkstra finishes A at distance 2, but S, B, A costs 1. Measure: compare with Bellman-Ford. Fix: use Bellman-Ford when weights can be negative.
Chapter 9
Keep the terms, the numbers, the code and the checks in one place
A greedy algorithm commits to the best-looking choice and never looks back. It is exact when the problem has the greedy-choice property and optimal substructure. The exchange argument is how you prove the first. A counterexample is how you disprove it.
| Term | Meaning | Number to remember |
|---|---|---|
| Activity selection | Sort by finish, keep each activity that starts at or after the last finish. | CLRS 11 activities: A, D, H, K |
| Greedy-choice property | Some optimal answer contains the greedy choice. | proved by one swap |
| Optimal substructure | The rest is a smaller copy whose best answer completes the whole. | induction on picks |
| Fractional knapsack | Take by value per kg; split the last item. | $240 at 50 kg |
| 0/1 knapsack | Whole items; needs DP. | greedy $160, best $220 |
| Huffman code | Merge the two rarest nodes until one is left. | abracadabra: 23 bits, fixed 33 |
| Entropy H | The floor on average bits per letter. | H ≤ L < H + 1 |
| Canonical coins | Coin sets where largest-first is always right. | 4, 3, 1 fails at 6 |
| Matroid | Hereditary sets with the exchange rule; greedy by weight is exact. | tasks: penalty 50 |
| Kruskal | Lightest edge that closes no cycle. | n − 1 edges |
pythonimport heapq from itertools import count def select_activities(acts): # acts: list of (start, finish) kept, last = [], float('-inf') for s, f in sorted(acts, key=lambda a: a[1]): if s >= last: # starts at or after the last finish kept.append((s, f)); last = f return kept def fractional_knapsack(items, W): # items: list of (weight, value) total = 0.0 for w, v in sorted(items, key=lambda x: x[1] / x[0], reverse=True): take = min(w, W); total += v * take / w; W -= take if W == 0: break return total def huffman(freq): # freq: dict letter -> count, 2+ letters tie = count() heap = [(f, next(tie), ch) for ch, f in freq.items()] heapq.heapify(heap) while len(heap) > 1: fx, _, x = heapq.heappop(heap) # the two rarest fy, _, y = heapq.heappop(heap) heapq.heappush(heap, (fx + fy, next(tie), (x, y))) codes = {} def walk(node, code): if isinstance(node, tuple): walk(node[0], code + '0'); walk(node[1], code + '1') else: codes[node] = code walk(heap[0][2], '') return codes def min_coins(coins, amount): # the DP for when greedy is not safe C = [0] + [float('inf')] * amount for a in range(1, amount + 1): C[a] = 1 + min((C[a - c] for c in coins if c <= a), default=float('inf')) return C[amount]
Huffman codes are part of real formats you use daily. DEFLATE, the method inside zip, gzip and PNG, codes its data with Huffman trees (RFC 1951). Baseline JPEG uses Huffman tables for its coefficients. HTTP/2 header compression uses a fixed Huffman code (RFC 7541).
Now press Present or Teach and explain from memory. Say why earliest finish is safe, with the swap. Say why the 0/1 bag gets $160 by greedy but $220 at best. Say what Huffman merges and why the cost is the sum of the merges. Then go back to the hall and run each rule again. This time say which chapter explains each result.
This lesson re-teaches Chapter 16, Greedy Algorithms, of Introduction to Algorithms (third edition) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). Huffman codes are due to David A. Huffman (1952). The text, toys and devices here are our own.