Not every greedy algorithm is about scheduling. A classic from data compression.
Problem: given how often each symbol appears, build a binary code
representing the whole message in as few bits as possible. Huffman's
rule never reconsiders a merge once it's made - exactly like
room-booking never reconsiders a granted booking. Like room-booking,
Huffman coding is provably optimal: it has both the greedy-choice
property and optimal substructure (full construction and proof:
CLRS §15.3, not required this week).
HUFFMAN(freqs):
make one leaf node per symbol,
weight = its frequency
while more than one node
remains:
take the two lowest-weight
nodes
merge into a new parent
node, weight = sum
return the last remaining node
(the tree root)
Huffman coding · worked example 1 of 3 (simple)
Three Symbols: A=2, B=3, C=5
The smallest case that still shows a merge, a tie, and real compression.
GoalBuild the tree for three symbols and compare against a fixed-length code.
1
Merge
Two smallest: A(2)+B(3) → AB(5). Two nodes left, AB(5) and C(5) - a tie. Merge them into the root(10).
0→F, 1100→A, 100→C, 111→E → "FACE". Weighted total: 224 bits, versus 300 at a fixed 3 bits/symbol.
✓
Conclusion5 symbols merge to 1 root in n−1 = 5 merges (always true for n symbols); FACE decodes unambiguously, left to right, no lookahead.
💡
Key takeawayThe more frequent a symbol, the shorter its path from the root - by construction, not by tuning.
Huffman coding · worked example 3 of 3 (harder)
A Second Message, Same Code Table
Same codes as FACE. A different bitstring - and why decoding it never needs to look ahead.
GoalDecode 10111111000 using F=0, C=100, D=101, E=111, A=1100, B=1101.
1
Setup
New bitstring: 10111111000. Decode left to right, matching one full code at a time.
→
2
Trace
101→D, 111→E, 1100→A, 0→F → message: "DEAF".
→
3
Why no lookahead
No code is a prefix of another (prefix-free). The instant read bits match one symbol's code, they cannot also be a partial prefix of a different, longer code.
★
Why it's guaranteed
Every symbol sits at a distinct tree leaf; a root-to-leaf path can never be a strict prefix of another such path. Prefix-free falls out of the tree structure itself, not a rule checked afterward.
✓
ConclusionDEAF decodes unambiguously with the same table that decoded FACE - one code table, many messages, zero ambiguity.
💡
Key takeawayPrefix-free isn't an extra rule bolted onto Huffman coding - it falls out of building the code from a tree's leaves for free.
When Greedy Fails: Campus Points
Two examples so far, both provably safe. Now: the same trick, quietly wrong.
CampusNav's gamification team adds a campus points reward
system: students earn points for attending events, and "spend" them
in fixed-value chunks at the campus store.
To keep the token design simple, the chosen values are {1, 3,
4} - not the familiar {1, 5, 10, 25}-style sets most coin systems use.
Checkout needs to give a student exactly 6 points of credit,
using as few tokens as possible. The obvious approach: reuse
this week's trick - greedily grab the largest token that still fits.
Campus points · counterexample 1 of 2
Denominations {1, 3, 4}, Target = 6
The obvious greedy rule: grab the largest token that still fits.
GoalCompare greedy's token count to the true optimal, on target 6.
1
Greedy trace
Take 4 (remaining 2). 3 doesn't fit, take 1 (remaining 1). Take 1 (remaining 0). Total: 4+1+1 = 3 tokens.
→
2
Optimal
3 + 3 = 6, using only 2 tokens.
→
3
The gap
Greedy uses 1 more token than necessary - silently, with no error or crash.
✓
ConclusionGreedy: 3 tokens (4+1+1). Optimal: 2 tokens (3+3). One counterexample is enough to disprove "greedy always finds the optimal."
💡
Key takeawayNothing about running the algorithm signals failure - it just quietly hands out one extra token, every time the balance is exactly 6.
Campus points · counterexample 2 of 2 (harder)
A Second Denomination Set: {1, 4, 5}, Target = 8
One counterexample could be a fluke. Here's an independent second one.
GoalShow a different denomination set fails the same way, and that passing a test proves nothing.
1
Greedy trace
Take 5 (remaining 3). Largest that fits is 1: take 1, 1, 1. Total: 5+1+1+1 = 4 tokens.
→
2
Optimal
4 + 4 = 8, using only 2 tokens - a different, independent counterexample.
→
3
Same shape of failure
Both counterexamples: greedy's "largest that fits" blocks a smaller-count pairing that would have worked.
★
Passing ≠ proof
The original {1,3,4} set, run at target 8 instead of 6: take 4, take 4 → 2 tokens, which happens to BE optimal. A failing example disproves "always" - but a passing example never proves it holds in general.
✓
Conclusion{1,4,5} at target 8 fails the same way as {1,3,4} at target 6 - two independent counterexamples, not a fluke of one number.
💡
Key takeawayTesting more targets is not a proof: {1,3,4} at target 8 happens to succeed, but that success says nothing about target 6's failure.
Fairness Sidebar: Efficient Isn't the Same as Fair
Even when greedy is provably optimal at its own goal, its goal might not be the only thing that matters.
The room-booking greedy rule is provably optimal at one specific
goal: maximizing the number of bookings granted.
But "earliest finish time" systematically favors short requests:
a single 3-hour workshop request competes against three separate
1-hour requests that fit around it, and the three short ones almost
always win, because they free up the room sooner.
Clubs that need long or complex bookings (a multi-hour rehearsal, a
full-day competition prep) get systematically deprioritized -
over a whole semester, the same handful of clubs see their requests
rejected far more often, purely as a side effect of a rule that was
never asked to consider fairness at all.
Naming the Tension
Provably optimal at one goal doesn't mean beyond challenge.
This is the efficiency-vs-fairness tension: a scheduler optimized for
one measurable goal (throughput) can be provably optimal at that goal
and still be worth challenging on a different, harder-to-measure goal
(fairness across request types). CampusNav's team has to choose
to weigh that trade-off - the algorithm alone won't do it for them.
CampusNav: This Week's Two Features
Everything above, together, on the actual app.
The room-booking assistant now ships with the earliest-finish-time
greedy scheduler, provably granting the maximum number of
non-overlapping bookings for Building A's shared seminar room - proof
included, not just "it worked in testing."
The campus points reward system deliberately keeps its {1, 3, 4}
denominations, as a teaching example baked into the app itself -
CampusNav's own team knows greedy change-making is wrong here, and
flags it as a known limitation rather than a silently-hidden bug.
Common Mistakes
"Greedy always finds the optimal solution." It doesn't - the
campus-points example gives a token-for-token counterexample: greedy
spends 3 tokens where 2 was possible. One counterexample is enough
to disprove "always."
Trusting a greedy rule because it "seemed to work" on the example
you tried. Exactly like the MAX bug from Week 2 - the
room-booking rule needed a full exchange-argument proof, not just
one 5-request trace, before we trusted it.
Confusing optimal substructure with the greedy-choice property.
Campus-points still has optimal substructure (the best way to make
6 does contain the best way to make some smaller remainder) - but
it's missing the greedy-choice property. Having one without the
other is exactly the gap that motivates Week 11's dynamic
programming, which needs only the first.
Key Words Today
Huffman coding: a greedy algorithm that builds an optimal compression code by repeatedly merging the two lowest-frequency symbols.
Fairness trade-off: a design tension where the choice that's most efficient (e.g. grants the most bookings) isn't necessarily the fairest one to every requester.
Denomination: one of the fixed "coin" values a change-making system is allowed to use, e.g. {1, 3, 4} campus points.
Non-overlapping: two intervals that share no time - the feasibility condition for room-booking.
Where Greedy Shows Up Beyond CampusNav
This isn't only about a seminar room.
Search "activity selection," "interval scheduling," or "greedy vs.
dynamic programming" in any technical interview question bank and
you'll find hundreds of problems - job/CPU scheduling, meeting-room
minimization, fractional knapsack, Huffman-style compression. The
transferable skill isn't memorizing which greedy rule to use - it's
recognizing when a problem has both required properties, and being
able to prove it, not just hope.
Compilers use a greedy register-allocation strategy; network routers
use greedy rules for some scheduling decisions; and "prove your greedy
choice is safe" is a standard whiteboard-interview request at major
tech companies precisely because so many candidates skip the proof.
What Greedy Cannot Do
Greedy is fast - one sorted pass, no backtracking - and when a problem
has both the greedy-choice property and optimal substructure, we can
now prove it, not just hope. But its local choices are
sometimes provably wrong, as the campus-points counterexample showed,
and there is no general shortcut for telling in advance whether a new
problem is "room-booking-shaped" or "campus-points-shaped." We need a
technique that considers the full choice space - without paying the
brute-force cost of trying every combination.
Next Week
Week 10 leaves problems where no single local choice is safe, but
brute-forcing every combination is too slow unsolved. Week 11,
Dynamic Programming I, addresses it: keeping every still-possibly-optimal
option alive at once, reusing overlapping subproblems, on CampusNav's
new Tour Planner feature.
Where This Week Lives in CLRS
Everything this week touched, mapped to its exact section.
Topic
CLRS 4th ed section
Activity-selection / interval scheduling
§15.1
Greedy-choice property, optimal substructure
§15.2
Huffman codes
§15.3
If you want to go deeper (not required this week):
fractional knapsack is a classic exercise for practicing exchange
arguments on a new problem; matroid theory (mentioned earlier today)
formalizes exactly which problems are guaranteed greedy-safe, beyond
checking case by case.
Summary
A greedy algorithm is safe only when a problem has both the
greedy-choice property and optimal substructure - CampusNav's
room-booking scheduler has both, proved by an exchange argument.
Campus-points ({1, 3, 4}, target 6) is a clean counterexample:
greedy spends 3 tokens where 2 was optimal - proof that "greedy
always works" is false in general.
A greedy algorithm can be provably optimal at its stated goal
(throughput) and still raise a fairness question (which requests get
systematically deprioritized) that the algorithm itself won't answer.
New: Week 10 Check - a short graded exercise on today's two
greedy techniques, released now, due before Week 11 begins, separate from Assignment 3 (also released this week, due Week
12) - see materials/assignments/week10-check.html.
Prepare: Assignment 3 is due Week 12 - start the exchange-argument
write-up early. Think about what CampusNav's Tour Planner (Week 11)
might need that neither last week's recursion nor this week's greedy
choice can safely provide.
Thank You
SLOT 1: Title
notes: Welcome the class. Open with the familiar experience that a quick decision, the option that looked best right then, can turn out worse once you see the whole picture.
That tension (locally best vs. globally best) is the whole week. Also flag that Assignment 3 is released today, due Week 12.
SLOT 2: Where we are
notes: Point at the row. Say: "Nine weeks in. Today CampusNav learns to make a single, local, never-revisited choice - and we'll prove exactly when that's safe."
SLOT 3: Recap + open wound
notes: This is Week 9's Limit slide, restated. It becomes today's pain, made concrete next slide.
SLOT: Assignment 3 announcement
notes: Mention this once, clearly, then move on - don't let logistics eat into the pain slide's momentum.
Key Words Today, session 1
notes: Read each term aloud once. Say: "greedy" gets a precise definition later this session; for now just recognize the words.
SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon
notes: Do not say "greedy," "recursion," or "algorithm design" yet. Let the class feel the mess first.
SLOT 5: Cost of not knowing
SLOT 6: Driving question
SLOT 7: Learning outcomes
SLOT 8: Origin
SLOT 9: Core concept
Key Words Today, session 2
notes: Read each term aloud. Say the exchange argument is the actual proof technique we build, step by step, this session.
Act 3 / BUILD
Idea + pseudocode merged into one slide
Dense worked example, room-booking, simple tier
Dense worked example, room-booking, moderate tier
Dense worked example, room-booking, harder tier (exchange-argument proof, flagship slide)
Idea + pseudocode for the second greedy technique
Dense worked example, Huffman, simple tier
Dense worked example, Huffman, moderate tier
Dense worked example, Huffman, harder tier (prefix-free proof, absorbs cut Check-Yourself)
Dense worked example, campus-points counterexample, simple tier
Dense worked example, campus-points counterexample, harder tier
SLOT N-2: Worked example
SLOT N-1: Common mistakes
Key Words Today, session 3
notes: Read each term aloud. Say: greedy and DP share vocabulary on purpose - Week 11 will pull on that thread.