Unit 3 of 6 · about 4 hours · derive

Greedy choice, optimal substructure and exchange arguments

Greedy is the shortest path from idea to code and the easiest place to be confidently wrong. The proof is the algorithm, so write it before the loop.

You'll be able to

  • State the greedy-choice property and optimal substructure of a new problem in one paragraph each, before writing any loop.
  • Prove a greedy rule with an exchange argument that preserves feasibility and never worsens the objective.
  • Prove a greedy rule with a staying-ahead invariant that compares the greedy prefix against every optimal prefix.

Covers

Greedy-choice property and optimal substructureExchange, staying-ahead and cut arguments
1

Read

In this order, only the parts listed

0 of 3 done

  1. Greedy thinking: when local choices win, and when they do notDSA Handbook - recursion, backtracking and greedy

    When greedy is provably correct: The exchange argument; Greedy stays ahead; A working example: Partition Labels

    Use the Where greedy fails section as a preview of the next unit. Counterexample drills live there.

  2. Huffman encodingDSA Handbook - recursion, backtracking and greedy

    The algorithm; Watching it run; Why Huffman codes are optimal prefix codes: the sibling exchange and the optimal-substructure step

  3. Greedy Algorithms, Chapter 4Algorithms - recursion, backtracking and greedy

    4.1 Storing Files on Tape for the first exchange argument, 4.3 General Pattern for the exchange template, and 4.4 Huffman Codes (printed pp. 159-170)

    Erickson proves everything by exchange; take stays-ahead from the handbook. Skip 4.5 Stable Matching.

2

Focus on

  • Exchange has a fixed shape: take an optimal solution, swap its first differing choice for the greedy one, show validity kept and the objective not worse, then induct on the rest.
  • Staying-ahead has a different shape: the greedy frontier dominates every optimal prefix at each step, as with Jump Game max reach. Pick the template that matches the state you can compare.
  • Optimal substructure must hold after the greedy choice. In Huffman coding, merging the two least frequent symbols leaves a smaller instance whose optimum sits inside the full optimum through the weight recurrence.
  • Partition Labels is the stays-ahead drill: last occurrence table, extend the part end, cut at , in time and extra space.
Common mistakes · 3
  • Proving by example. Passing samples shows the code runs; only the exchange or staying-ahead step shows no optimal solution beats it.
  • An exchange that breaks feasibility. Swapping must keep the prefix-free sibling structure in Huffman coding and disjointness in scheduling, or the transformed optimum is not a valid candidate.
  • Staying ahead on a measure that does not imply the objective. Largest-coin-first on coins [1, 3, 4] with target 6 leads on amount covered after one coin (4 against 3), yet needs 3 coins () against the optimal 2 ().
3

Try it yourself

Closed-book, before checking anything

From a blank file in Python 3.13.14, implement Partition Labels from its invariant and run it on ababcbacadefegdehijhklij to get [9, 7, 8]. Closed book, write the Huffman exchange step: swapping a least frequent symbol into a deepest sibling leaf changes total cost by at most zero.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.When do you reach for exchange, and when for staying-ahead?Answer

    Exchange fits when any optimum can be rewritten choice by choice into greedy form. Staying-ahead fits when greedy maintains a frontier, such as reach or coverage, that dominates every optimal prefix at each step.

  2. 2.State the Huffman exchange computation.Answer

    Let be a least frequent symbol and a deepest leaf. Swapping their positions changes weighted path length by , which is at most zero since is at least and is at most . Repeat until the two least frequent symbols are deepest siblings.

  3. 3.Why does at least zero guarantee a valid start?Answer

    Start after the station where cumulative surplus hits its minimum. Every partial sum from there stays nonnegative, so the tank never empties over the full circuit.

  4. 4.What optimal-substructure claim does Huffman coding need after the greedy merge?Answer

    Merging the two least frequent symbols into one parent leaves a smaller coding instance, and an optimal tree for the smaller instance extends to an optimal tree for the original through the weight recurrence.

5

Practice

  • LeetCode 134: Gas Station

    Attempt cold. Example gas [1, 2, 3, 4, 5] with cost [3, 4, 5, 1, 2] returns 3; gas [2, 3, 4] with cost [3, 4, 3] returns minus 1.

    After submitting, read the DSA Handbook Jump games and gas station chapter (Claims 1 and 2) and the AlgoMaster Gas Station lesson (https://algomaster.io/learn/dsa/gas-station), and restate your loop invariant in their terms.

You're done when

Gas Station is accepted from a cold attempt, and you can write the Huffman exchange step and the total-surplus argument without notes.

Only when you can do this without notes.

Leads to

Notes

Resources · 2 for this unit, 3 more in the section

Also in this section

  • AlgoMaster DSA - decomposition and greedy sliceAlgoMaster · required

    Attempt N-Queens and Gas Station cold, then implement reservoir sampling and test its output distribution over fixed-seed trials. Add another judged problem only for a diagnosed weakness.

  • MIT 6.042J - probability and randomized algorithmsMIT OpenCourseWare · support

    Use the probability, expectation and concentration readings to derive sampling probabilities and distinguish expected from high-probability guarantees.

  • Algorithms lecture notes - randomized algorithmsJeff Erickson · support

    Use note 1 Discrete Probability, note 2 Nuts and Bolts (randomized quicksort, with QuickSelect in its exercises), note 4 Tail Inequalities and note 5 Hashing to derive expected costs, separate expected from high-probability guarantees, and analyze hashing behavior.