Skip to content

Lesson 22 of 27Decode by category

Decoding DP and Greedy

Tell dynamic programming from greedy from backtracking, break a greedy idea with a counterexample, and find the DP state.

16 min read0/5 questions

Dynamic programming, greedy, and backtracking all solve problems made of choices: which coin, which house, which item next. That is why they get confused. Pick greedy when the problem needs DP and your code passes the examples but fails hidden tests. Pick backtracking when it needs DP and you time out. Interviewers know this, and "why does greedy work here?" is one of their favourite follow-ups.

This lesson gives you the wording clues, a way to test a greedy idea in under a minute, and a recipe for finding the DP state. For how each family works, see Dynamic Programming, Greedy Algorithms and Backtracking in the Algorithms & Patterns course.

Three families, one question each

FamilyWhat it doesAsk yourself
GreedyMakes the locally best choice and never looks back"Can one choice ever be regretted later?" If never, greedy.
Dynamic programmingTries every choice, but remembers answers to repeated subproblems"Do different choice paths lead to the same situation?"
BacktrackingTries every choice and builds every full answer"Do I need to list every answer, not just count or optimise?"

Wording clues

WordingUsuallyWhy
"count the number of ways"DPCounting does not need the answers themselves, so overlapping paths can be merged.
"minimum / maximum cost, coins, steps" with choicesDP, sometimes greedyOptimising over choices. Greedy only if a local rule is provably safe.
"return all combinations / permutations / partitions"BacktrackingThe output itself is exponential. Nothing can beat listing it.
"can you reach the end / is it possible"Greedy or DPOften a single reach value suffices (Jump Game).
"longest / shortest subsequence"DPSubsequences skip elements, so choices branch.
"schedule as many as possible", intervalsGreedy (sort by end)The earliest-finishing choice never hurts.
"two strings", "edit", "match"2D DP over (i, j)Each state is a prefix of each string.

The difference between "count" and "list" is the most important line in that table. Number of subsets that sum to k: DP. All subsets that sum to k: backtracking.

Match the pairs0/5 matched

Match each prompt to its family.

Choose an item, then its match on the other side.

Testing a greedy idea: hunt for a counterexample

Greedy is fast and short, so it is tempting. Before you commit, spend one minute trying to break it on a tiny input. If you cannot break it after a few honest tries, explain why the local choice is safe. If you can, you have just proved you need DP, and saying so out loud is a strong signal.

The classic: fewest coins. Greedy takes the biggest coin that fits. With US coins (1, 5, 10, 25) that is optimal. With coins [1, 3, 4] and amount 6:

Predict the outputPython

What does this print?

coins = [4, 3, 1]
amount, used = 6, 0
for c in coins:
  used += amount // c
  amount %= c
print(used)
Need a nudge? Hints walk you through it.

You do not have to find counterexamples by hand. A brute-force DP and a few lines of search will do it, and this is a habit worth keeping when you practice:

Pythonbreak_greedy.py
def greedy(coins: list[int], amount: int) -> int: used = 0 for c in sorted(coins, reverse=True): used += amount // c amount %= c return used if amount == 0 else -1 def best(coins: list[int], amount: int) -> int: INF = float("inf") dp = [0] + [INF] * amount for a in range(1, amount + 1): for c in coins: if c <= a: dp[a] = min(dp[a], dp[a - c] + 1) return dp[amount] if dp[amount] != INF else -1 for coins in ([1, 5, 10, 25], [1, 3, 4], [1, 7, 10]): bad = [a for a in range(1, 40) if greedy(coins, a) != best(coins, a)] print(coins, "greedy wrong at:", bad[:5])
Output
Press Run (⌘ Enter) to see what happens.
Quick check
To fit the most non-overlapping meetings, someone proposes: sort by start time and take each meeting that does not overlap the last one taken. Which input breaks it?
Need a nudge? A hint rules out a wrong answer.

Finding the DP state

Once you know it is DP, the hard part is the state: the smallest set of facts that fully describes "where you are" in the problem. A good test: what do I need to know to finish the rest of the problem optimally? Whatever that is, it is the state.

ProblemStateWhy that is enough
Climbing Stairsi: the current stepThe ways to finish from step i do not depend on how you got there.
House Robberi: houses considered so farBest loot up to i is either best up to i − 1, or house i plus best up to i − 2.
Coin Changea: the amount leftWhich coins you used before does not matter, only what remains.
Longest Common Subsequence(i, j): a prefix of each stringEach choice consumes from one string or both.
Stock with Cooldown(day, holding?, cooling?)A flag is part of the state when it changes what you may do next.

The constraints check your choice. The DP table has one cell per state, so the number of states times the work per state must fit the budget. Two strings of length 1000 give 10^6 states, fine. An amount up to 10^4 with 12 coins gives 1.2 × 10^5 steps, fine.

Here is the coin change table for [1, 3, 4], amount 6. Each cell is the fewest coins for that amount, built from smaller amounts.

Coin change: dp[a] = fewest coins for amount a
0123456
dp0

Amount 0 needs 0 coins. That is the base case.

1/4
Quick check
House Robber II puts the houses in a circle, so the first and last are neighbours. What is the cleanest way to adapt the state?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

Put the steps for building a DP solution in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Constraint tells

ConstraintSuggests
n <= 20 and "all" or "every"Backtracking (2^20 is about a million)
n <= 1000 with two sequencesO(n · m) DP over (i, j)
n <= 10^5, one pass feels possibleGreedy or O(n) DP with a few variables
An amount or target up to 10^4DP indexed by the amount
Answer "modulo 10^9 + 7"Counting DP. The count is too big to list, so it is not backtracking.

That last one is a gift. If the answer must be returned modulo a large prime, the number of ways is astronomical, which rules out listing them.

In the Decoder, DP and greedy problems list each other as decoys. Before revealing the decoy stage, try to name the counterexample (for DP problems) or the reason greedy is safe (for greedy problems).

ChallengeMedium

Coin Change

You have unlimited coins of each value in coins. Return the fewest coins that add up to exactly amount, or -1 if no combination works.

coins = [1, 2, 5], amount = 11  →  3    (5 + 5 + 1)
coins = [2], amount = 3         →  -1
coins = [1], amount = 0         →  0

Constraints

  • 1 <= coins.length <= 12
  • 1 <= coins[i] <= 2^31 - 1
  • 0 <= amount <= 10^4
def coin_change(coins: list[int], amount: int) -> int: # Work out the fewest coins for every amount from 0 up to the target. pass
ChallengeMedium

Jump Game

You stand on index 0 of nums. From index i you may jump forward up to nums[i] places. Return true if you can reach the last index.

nums = [2, 3, 1, 1, 4]  →  true    (0 → 1 → 4)
nums = [3, 2, 1, 0, 4]  →  false   (every route lands on the 0 at index 3)
nums = [0]              →  true    (you start at the end)

Constraints

  • 1 <= nums.length <= 10^4
  • 0 <= nums[i] <= 10^5
def can_jump(nums: list[int]) -> bool: # Track the furthest index you can reach so far. pass
Key terms
greedy choice
A locally best choice that is never regretted. Must be justified, usually by an exchange argument.
counterexample
A small input where an approach gives the wrong answer. One is enough to rule greedy out.
DP state
The smallest set of facts that describes a subproblem: what you need to know to finish the rest.
recurrence
The rule that builds a state's answer from smaller states, like dp[a] = min(dp[a - c] + 1).
exchange argument
Proof that swapping any optimal first choice for the greedy one never makes the answer worse.