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.
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
| Family | What it does | Ask yourself |
|---|---|---|
| Greedy | Makes the locally best choice and never looks back | "Can one choice ever be regretted later?" If never, greedy. |
| Dynamic programming | Tries every choice, but remembers answers to repeated subproblems | "Do different choice paths lead to the same situation?" |
| Backtracking | Tries every choice and builds every full answer | "Do I need to list every answer, not just count or optimise?" |
Wording clues
| Wording | Usually | Why |
|---|---|---|
| "count the number of ways" | DP | Counting does not need the answers themselves, so overlapping paths can be merged. |
| "minimum / maximum cost, coins, steps" with choices | DP, sometimes greedy | Optimising over choices. Greedy only if a local rule is provably safe. |
| "return all combinations / permutations / partitions" | Backtracking | The output itself is exponential. Nothing can beat listing it. |
| "can you reach the end / is it possible" | Greedy or DP | Often a single reach value suffices (Jump Game). |
| "longest / shortest subsequence" | DP | Subsequences skip elements, so choices branch. |
| "schedule as many as possible", intervals | Greedy (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 each prompt to its family.
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:
What does this print?
coins = [4, 3, 1] amount, used = 6, 0 for c in coins: used += amount // c amount %= c print(used)
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:
Press Run (⌘ Enter) to see what happens.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.
| Problem | State | Why that is enough |
|---|---|---|
| Climbing Stairs | i: the current step | The ways to finish from step i do not depend on how you got there. |
| House Robber | i: houses considered so far | Best loot up to i is either best up to i − 1, or house i plus best up to i − 2. |
| Coin Change | a: the amount left | Which coins you used before does not matter, only what remains. |
| Longest Common Subsequence | (i, j): a prefix of each string | Each 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.
Amount 0 needs 0 coins. That is the base case.
Put the steps for building a DP solution in order.
- Tap the steps below in the right order.
Constraint tells
| Constraint | Suggests |
|---|---|
n <= 20 and "all" or "every" | Backtracking (2^20 is about a million) |
n <= 1000 with two sequences | O(n · m) DP over (i, j) |
n <= 10^5, one pass feels possible | Greedy or O(n) DP with a few variables |
An amount or target up to 10^4 | DP 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).
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 → 0Constraints
1 <= coins.length <= 121 <= coins[i] <= 2^31 - 10 <= amount <= 10^4
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^40 <= nums[i] <= 10^5
- 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.