Greedy algorithms

In one sentence

Take the locally best choice at each step and never undo it; it is correct only when you can prove, usually with an exchange argument, that the choice never rules out an optimal solution.

Greedy is a claim to test: hunt for a small counterexample first, then prove the rule with an exchange argument. Only then is the sort-and-take loop safe.

How it works

  • Sort or keep a heap, take the best candidate by one rule, never undo it.
  • Exchange argument: swap the greedy choice into any optimal solution without making it worse.
  • One counterexample kills a rule: coins {1, 3, 4} for 6 give 4 + 1 + 1; DP finds 3 + 3.
  • Interval scheduling: the earliest finish wins because it leaves the most room for the rest.
  • Furthest reach: one number, the furthest reachable index, summarizes every jump option so far.

Check yourself

Answer to mark it learned; your answers aren't scored.

Fewest coins for an amount, with denominations given as input. Your largest-coin-first solution passes the samples (1, 5, 10, 25) but fails a hidden test: coins {1, 3, 4}, amount 6. What now?

Go deeper

Solve it in Python 11
Full explanation

A greedy algorithm builds the answer one choice at a time: sort (or keep a heap), take the best candidate by one rule, never reconsider. That makes it fast, O(n log n) or O(n), and easy to get wrong: several rules sound right and usually only one is.

Prove it with an exchange argument. Take any optimal solution that differs from yours. Show that swapping its first different choice for the greedy one doesn't make it worse. Repeat, and the optimal solution turns into the greedy one. Interval scheduling (Interval problems: sort and sweep): the meeting that ends first leaves at least as much room as any other first pick.

Disprove it with one counterexample. Coins {1, 3, 4}, amount 6: largest-first gives 4 + 1 + 1, three coins; the best is 3 + 3. When no rule survives, compare every choice with Dynamic Programming.

Furthest reach: in jump problems, keep the furthest index reachable so far. Every index before it is reachable too, so one number summarizes all the options.

Code Furthest reach, and greedy vs DP on coins
pythonFurthest reach, and greedy vs DP on coins
def can_reach_end(jumps: list[int]) -> bool:
    reach = 0                                # furthest index reachable so far
    for i, j in enumerate(jumps):
        if i > reach:                        # no earlier jump gets here: stuck
            return False
        reach = max(reach, i + j)
    return True

def min_jumps(jumps: list[int]) -> int:      # assumes the end is reachable
    hops = end = reach = 0
    for i in range(len(jumps) - 1):          # never jump FROM the last index
        reach = max(reach, i + jumps[i])
        if i == end:                         # this hop's range is used up: must jump
            hops, end = hops + 1, reach      # commit to the furthest reach
    return hops

def greedy_coins(coins: list[int], amount: int) -> int:
    used = 0
    for c in sorted(coins, reverse=True):    # largest coin first, never undone
        used, amount = used + amount // c, amount % c
    return used if amount == 0 else -1       # optimal only for canonical coin systems

def dp_coins(coins: list[int], amount: int) -> int:
    INF = float("inf")
    best = [0] + [INF] * amount              # best[a] = fewest coins that make a
    for a in range(1, amount + 1):
        best[a] = min((best[a - c] + 1 for c in coins if c <= a), default=INF)
    return best[amount] if best[amount] < INF else -1

assert greedy_coins([1, 3, 4], 6) == 3 and dp_coins([1, 3, 4], 6) == 2   # 4+1+1 vs 3+3
Real example

Jump game: each value is the longest jump allowed from that index. [2, 3, 1, 1, 4]: reach is 2 after index 0 and 1 + 3 = 4 after index 1, the last index, so the end is reachable (in 2 jumps: 0 → 1 → 4). [3, 2, 1, 0, 4]: reach stays at 3 through indexes 0–3, and index 4 > 3, so you are stuck. One O(n) pass and one variable, versus an O(n²) DP that marks every reachable index.

Trade-offs +3 · −3

+ You gain

  • Fast and small: usually one sort plus one pass, with O(1) extra state.
  • Exact when proven, not a heuristic: Dijkstra, Kruskal and Huffman coding are greedy.
  • Short code once you have the right rule.

− You pay

  • Correct only for some problems; a plausible rule can be silently wrong.
  • The proof is the hard part, and interviewers ask for it.
  • Fragile: add weights to the intervals and earliest-finish stops working; that version needs DP.

Use it when

"Maximum number of…" or "minimum number of…" where sorting by one key (end time, deadline, ratio) or always taking the current best from a heap is provably safe: scheduling, jump reach, Huffman-style merging.

Avoid it when

A small counterexample breaks every rule you try, or choices interact: 0/1 knapsack, arbitrary coin sets, weighted intervals. Use DP; if you need every solution, backtracking.

Numbers to know 4
  • Typical cost: O(n log n) for the sort, then O(n). Jump game: O(n) time, O(1) space.
  • Coins {1, 3, 4}, amount 6: greedy uses 3 coins (4 + 1 + 1); the optimum is 2 (3 + 3).
  • US coins without the nickel, {25, 10, 1}, for 40¢: greedy uses 7 coins; the optimum is 4 (4 × 10).
  • Coin change by DP: O(amount × number of coin values).
Common pitfalls 4
  • Coding the first rule that sounds right without trying a small counterexample.
  • Interval scheduling sorted by start time or by duration instead of by end time.
  • Greedy on 0/1 knapsack or arbitrary coins. Value-per-weight is only optimal when items can be split.
  • Jump game without the i > reach check: unreachable indexes extend the reach.
Interview questions 3

Answer out loud first, then reveal.

How do you know a greedy solution is correct?Show answer

I don't trust it until I've done two things. First I try to break it with tiny inputs: ties, one long item against two short ones. If it survives, I sketch an exchange argument: take an optimal solution, swap its first different choice for mine and show the result is no worse. If I can't make the swap work, I say so and move to DP, which is slower but safe.

Minimum number of jumps to reach the last index?Show answer

It's BFS by levels, done greedily. I keep the end of the current jump's range and the furthest index reachable from anywhere inside it. When I reach the end of the range I have to jump, so I count one and extend the range to that furthest reach. Each index is visited once: O(n) time, O(1) space. It's safe because the furthest reach covers every index a shorter jump could land on.

Coin change: greedy or DP?Show answer

It depends on the coin set. For canonical systems, like US or euro coins, largest-first is optimal. For arbitrary coins it isn't: {1, 3, 4} for 6 gives three coins instead of two. An interview problem with arbitrary denominations means DP over amounts, O(amount × coins). I'd mention greedy only as an optimization when the system is known to be canonical.