interviewpath
  • 0day streak
  • 10total XP
  • Level 1
0/6

Unit 1 · Algorithms · Lesson 17 of 24

Greedy algorithms and exchange arguments

A greedy algorithm commits to the locally best choice and never revisits it; it is correct only when an argument shows that some optimal solution agrees with every choice. Interviewers use greedy problems to see whether you can give that argument, usually an exchange argument, or find a counterexample that sends you to dynamic programming instead.
About 4 hFocus mode

Step 1: Learn the ideas

  • Greedy-choice property and optimal substructure
  • Exchange arguments
  • Greedy stays ahead
  • Interval scheduling, covering and removal
  • Searching for counterexamples to candidate rules
  • Sort keys and tie-breaking
  • Heap-driven greedy choices
  • Greedy versus DP: weighted intervals, knapsack, coin systems

Why it matters

Greedy solutions are short and fast, but a rule that feels right is wrong surprisingly often. That makes greedy problems a good probe of reasoning: an interviewer wants to hear why the rule is safe, not only see that it passes the examples. Real systems use greedy decisions everywhere (Huffman coding, Kruskal's and Prim's spanning trees, scheduling and packing heuristics), and knowing when a greedy choice is provably optimal versus merely good is valuable engineering judgement.

Core ideas

A greedy algorithm needs two properties. Greedy choice: some optimal solution contains the first greedy choice. Optimal substructure: after that choice, what remains is a smaller instance of the same problem. Together they give an induction: the first choice is safe, and the remainder is again solved greedily.

Exchange argument, worked sketch. Interval scheduling asks for the largest set of pairwise non-overlapping intervals. Rule: sort by end time and take each interval that starts at or after the end of the last one taken.

  1. Let g be the interval with the earliest end. Take any optimal solution O and let o be its interval with the earliest end.
  2. Replace o with g. Every other interval in O starts at or after o ends, and g ends no later than o, so the new set is still non-overlapping and has the same size. Hence some optimal solution contains g.
  3. Remove g and every interval overlapping it. What remains is the same problem on a smaller input, and induction finishes the proof.

The general recipe: take an optimal solution that first differs from greedy at some step, swap in the greedy choice, and show the result is still feasible and no worse.

Greedy stays ahead. Show by induction that after each step, greedy's partial solution is at least as good as any other solution's after the same number of steps. For jump-style reachability the invariant is the farthest index reachable from the positions scanned so far; for the minimum number of jumps, scanning in BFS-like layers keeps greedy's reach after k jumps at least that of any strategy.

Counterexamples are part of the method. For interval scheduling, earliest start fails when one long interval covers two short disjoint ones, and shortest-first fails when a short interval overlaps two disjoint longer ones. For coin change, largest-coin-first is optimal for systems such as 1, 5, 10, 25 but not in general: with coins 1, 3 and 4 and target 6 it uses 4 + 1 + 1 instead of 3 + 3. Spend a couple of minutes trying to break a rule on tiny inputs before committing to it.

When greedy fails, think DP. Weighted interval scheduling, 0/1 knapsack and general coin change have choices that interact, so a local rule cannot account for what it gives up; dynamic programming over sorted order or over capacity fixes this. Fractional knapsack, by contrast, is greedy by value per unit weight because items can be split.

Implementation shape. Most greedy solutions are "sort by a key, then one scan" in O(n log n), or "repeatedly take the best available item from a heap". The key and the tie-breaking are the algorithm, so state them explicitly.

Common misconceptions

  • "If it passes the examples, the rule is right." Examples are chosen to be readable, not adversarial. Search for a counterexample, then argue correctness.
  • "Interval problems always sort by start." Merging overlaps sorts by start; maximizing compatible intervals or minimizing removals sorts by end. The objective decides the key.
  • "An exchange argument shows greedy equals the optimal solution." It shows that some optimal solution can be transformed to agree with greedy without getting worse; the optimum need not be unique.
  • "Greedy and DP are unrelated." A greedy algorithm is a DP in which one choice is provably always best, so only one subproblem is solved. When you cannot prove that, fall back to the DP.
  • "Largest-first works for coin change." Only for some coin systems; arbitrary denominations need DP.

How to approach it

Propose the rule, then test it immediately against two or three tiny adversarial inputs, saying what you are checking. If it survives, give a short argument in words: "swap the first differing choice for the greedy one; it stays feasible because...; the objective does not get worse because...". Then code the sort-and-scan and state the complexity. Graduate interviews usually accept a convincing informal argument; mid and senior interviews push harder on ties, equal endpoints and empty input, and on what changes when weights are added.

Suggested order

  1. 1Read MIT 6.046J Lecture 1 (Overview, Interval Scheduling) for the earliest-finish-time proof and the weighted variant where greedy fails.
  2. 2Read Erickson Ch. 4 (Greedy Algorithms), the sections on storing files on tape, scheduling classes and the general pattern; then rewrite the class-scheduling exchange argument in your own words in about five lines.
  3. 3For interval scheduling, write three candidate rules and find a counterexample for each wrong one before coding the right one.
  4. 4Solve Jump Game, then Non-overlapping Intervals and Minimum Number of Arrows to Burst Balloons, stating the argument aloud for each.
  5. 5Solve Gas Station and explain why a failed start rules out every start in between; then Jump Game II with a layered stays-ahead invariant.
  6. 6Solve Partition Labels and Two City Scheduling (derive the sort key by exchanging two people), then Hand of Straights, Task Scheduler and Valid Parenthesis String as review items.

Step 2: Check off what you can do

Tap each one you can genuinely do or explain. Each earns 10 XP.

Step 3: Go deeper

  • Algorithms (Jeff Erickson) with companion lecture notesStart here

    Jeff Erickson, University of Illinois Urbana-Champaign

    Section: Ch. 4: Greedy Algorithms

    Exchange arguments developed carefully on storing files on tape and scheduling classes (interval scheduling), then distilled into a general pattern; later sections cover Huffman codes and stable matching.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • MIT 6.046J Design and Analysis of Algorithms (Spring 2015)Start here

    MIT OpenCourseWare

    Section: Lecture 1: Overview, Interval Scheduling

    Short notes comparing candidate greedy rules, proving earliest finish time by induction and motivating DP for the weighted version.

    Open(opens in a new tab)Link responded, 5 Oct 2026
  • Competitive Programmer’s Handbook

    CSES

    Section: Ch. 6: Greedy algorithms

    Compact examples (coins, scheduling, tasks and deadlines) with brief correctness arguments and counterexamples.

    Open(opens in a new tab)Link responded, 5 Oct 2026

Step 4: Practice

For every problem, write the greedy rule, one counterexample you tried against it, and a two-sentence exchange or stays-ahead argument before coding. If you cannot argue the rule, say so and consider a DP; making that judgement is part of what you are practicing. Keep the later items for review rotation.

Record attempts on each problem’s page (+15 XP, +10 more when solved on your own).

Step 5: Test yourself

Answer each one out loud or on paper before you finish the lesson.

  1. Question 1Which two properties must hold for a greedy algorithm to be optimal?
  2. Question 2Walk through the exchange argument for earliest-end-time interval scheduling.
  3. Question 3Which sort key merges intervals, which maximizes non-overlapping intervals, and why do they differ?
  4. Question 4Give a coin system and target for which largest-coin-first fails.
  5. Question 5What is a stays-ahead argument, and on which problem did you use one?
  6. Question 6How can you gain confidence in a greedy rule during an interview if a full proof is out of reach?

You’re done when you can

  • Write the interval-scheduling exchange argument from memory in under five minutes.
  • Produce counterexamples of at most four elements for three plausible but wrong greedy rules.
  • Solve an unseen greedy problem in under 25 minutes and state why the rule is safe.
  • Explain why weighted interval scheduling and general coin change need dynamic programming.

Finish the lesson

How confident do you feel?

Lesson complete!

+50 XP

Reviews will come up on the Practice tab so it sticks.

Your notes and study time

Log study time