Dynamic Programming
Reach for it when the problem says
- Count the ways
- min/max cost
- "can you reach…"
- overlapping choices
- Solved
- 0/36Solved
- Problems
- 36Problems
- Variants
- 6Variants
Problems
6 variantsLinear 1D
0 of 9 solved- Climbing StairsUp nextSprintDeep diveEasyDecode Climbing Stairs
- Min Cost Climbing StairsEssentialsDeep diveEasyDecode Min Cost Climbing Stairs
- N-th Tribonacci NumberEssentialsDeep diveEasyDecode N-th Tribonacci Number
- House RobberEssentialsSprintDeep diveMediumDecode House Robber
- House Robber IIMediumDecode House Robber II
- Delete and EarnMediumDecode Delete and Earn
- Domino and Tromino TilingEssentialsDeep diveMediumDecode Domino and Tromino Tiling
- Decode WaysMediumDecode Decode Ways
- Longest Increasing SubsequenceSprintDeep diveMediumDecode Longest Increasing Subsequence
State machine
0 of 5 solved- Maximum Product SubarrayMediumDecode Maximum Product Subarray
- Best Time to Buy and Sell Stock with CooldownMediumDecode Best Time to Buy and Sell Stock with Cooldown
- Best Time to Buy and Sell Stock with Transaction FeeEssentialsDeep diveMediumDecode Best Time to Buy and Sell Stock with Transaction Fee
- Best Time to Buy and Sell Stock IIISprintDeep diveHardDecode Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IVSprintDeep diveHardDecode Best Time to Buy and Sell Stock IV
Knapsack
0 of 7 solved- Coin ChangeSprintDeep diveMediumDecode Coin Change
- Coin Change IIMediumDecode Coin Change II
- Partition Equal Subset SumMediumDecode Partition Equal Subset Sum
- Target SumMediumDecode Target Sum
- Combination Sum IVMediumDecode Combination Sum IV
- Perfect SquaresMediumDecode Perfect Squares
- Word BreakSprintDeep diveMediumDecode Word Break
Grid paths
0 of 6 solved- Unique PathsEssentialsDeep diveMediumDecode Unique Paths
- Unique Paths IISprintDeep diveMediumDecode Unique Paths II
- Minimum Path SumSprintDeep diveMediumDecode Minimum Path Sum
- TriangleSprintDeep diveMediumDecode Triangle
- Maximal SquareSprintDeep diveMediumDecode Maximal Square
- Longest Increasing Path in a MatrixHardDecode Longest Increasing Path in a Matrix
Two strings
0 of 5 solved- Longest Common SubsequenceEssentialsDeep diveMediumDecode Longest Common Subsequence
- Interleaving StringSprintDeep diveMediumDecode Interleaving String
- Edit DistanceEssentialsSprintDeep diveHardDecode Edit Distance
- Distinct SubsequencesHardDecode Distinct Subsequences
- Regular Expression MatchingHardDecode Regular Expression Matching
Interval DP
0 of 4 solvedPattern guide
Dynamic programming (DP) is the pattern interviewers use to separate people who memorised answers from people who can build one. Every DP problem asks the same two questions: what is the state, and how does one state follow from smaller ones? Answer those out loud and the code is usually ten lines.
What it is
A problem is a DP problem when two things are true. First, the answer can be built from answers to smaller versions of the same problem (this is called optimal substructure). Second, a plain recursive solution would solve the same smaller problems many times (overlapping subproblems). DP solves each smaller problem once, stores the result in a table, and reads it back.
Take House Robber: houses hold coins, and you cannot rob two neighbours. Brute force tries every allowed subset, which is O(2ⁿ). But the best haul from the first i houses only depends on two smaller answers: the best from the first i - 1 houses (skip house i) and the best from the first i - 2 houses plus house i (rob it). Watch the table fill.
Houses hold [2, 7, 9, 3, 1]. best[i] will be the most coins from houses 0..i.
Every DP solution you write has the same four parts:
- State: what one cell of the table means, in one sentence ("
best[i]is the most coins from houses0..i"). - Recurrence: how a cell is computed from smaller cells.
- Base cases: the cells you know without computing.
- Order: fill cells so every cell's inputs are ready before you need them, then read off the answer.
You can implement it top-down (recursion plus a memo, a cache keyed by the arguments) or bottom-up (loops filling a table). They do the same work. Bottom-up avoids recursion depth limits and makes space savings obvious; top-down is easier when the fill order is awkward.
How to recognise it
Wording clues
| Phrase in the prompt | What it suggests |
|---|---|
| "how many ways", "number of distinct" | Counting DP: add the counts of smaller states |
| "minimum cost", "fewest", "maximum profit" | Optimisation DP: min or max over choices |
| "can you reach", "is it possible to split" | Boolean DP: OR over choices |
| "subsequence" (not substring) | Characters can be skipped: a prefix or interval table |
| "two strings", "transform a into b" | 2D table over (prefix of a, prefix of b) |
| "you cannot pick two adjacent", "cooldown" | Take-or-skip, or a small state machine per index |
| "unlimited supply", "use each at most once" | Knapsack: sweep upward vs downward |
Constraint clues
| Constraint | What it suggests |
|---|---|
n <= 20 | 2ⁿ may pass; bitmask DP or backtracking |
n <= 500 to n <= 1000 with two strings | O(n · m) table, about 10^6 cells |
n <= 300 with ranges | O(n³) interval DP is the intended budget |
n <= 10^5 | O(n) or O(n log n): a 1D DP with O(1) work per cell |
amount <= 10^4, sum <= 1000 | A table indexed by value is cheap |
| "return the answer modulo 10^9 + 7" | Counting with huge results: almost always DP |
Input and output shape clues
- One array, answer is one number (best sum, count of ways): Linear 1D.
- Rules that depend on what you did yesterday (holding a stock, cooldown): State machine.
- A target total and a list of item values: Knapsack.
- A grid with right and down moves: Grid paths.
- Two strings: Two strings.
- One string or array where the answer for a range uses smaller ranges inside it (palindromes, bursting): Interval DP.
Looks like it but isn't
| It smells like DP, but... | Use instead |
|---|---|
| "Return all combinations / permutations" | Backtracking. You must list them, and caching a count does not help. |
| A local choice is provably safe (Jump Game, interval scheduling) | Greedy. DP works but is slower than it needs to be. |
| Shortest path with arbitrary moves or weights in a grid | BFS or Dijkstra. DP needs an order with no cycles. |
| Contiguous subarray with a monotonic rule (sum at most k, all positives) | Sliding window. |
The sub-patterns
Linear 1D
When it applies: one sequence, and the answer at position i depends on a fixed number of earlier positions (i - 1, i - 2, sometimes every j < i). The state is "the answer for the prefix ending at i". When each cell looks back a constant number of places, roll a few variables instead of storing the table.
Base cases: one way to stand on step 0 and one way to reach step 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n) time, O(1) space with rolling variables. When each cell scans all earlier cells (Longest Increasing Subsequence), it is O(n²).
Best-known problems: Climbing Stairs, House Robber, Decode Ways, Longest Increasing Subsequence.
What does this print?
prev, curr = 0, 0 for coins in [2, 1, 1, 2]: prev, curr = curr, max(curr, prev + coins) print(curr)
State machine
When it applies: at each index you can be in one of a few modes (holding a stock or not, just sold, cooling down), and the rules say which mode can follow which. The state is (index, mode). Draw the modes as boxes with arrows; each arrow is one term in a recurrence. Maximum Product Subarray fits too: the two modes are "largest product ending here" and "smallest product ending here".
Before day 0 you cannot hold anything, so hold = -∞.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n · k) for k modes, which is O(n) for the usual two or three. Space is O(k).
Best-known problems: Best Time to Buy and Sell Stock with Cooldown, Best Time to Buy and Sell Stock with Transaction Fee, Maximum Product Subarray.
Knapsack
When it applies: you have items (coins, numbers, words, squares) and a target total, and you pick items to hit it: fewest items, number of ways, or whether it is possible. The state is indexed by the total, not by position. Two flavours:
- Unbounded (each item reusable): sweep totals upward, so a total can build on a smaller total that already used the same item.
- 0/1 (each item once): for each item, sweep totals downward, so
table[t - item]still describes the world before this item.
When counting, loop order also decides what you count: items outside counts combinations; totals outside counts ordered sequences.
fewest[0] = 0: zero coins make zero. Everything else starts as impossible.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n · T) time for n items and target T, O(T) space.
Best-known problems: Coin Change, Coin Change II, Partition Equal Subset Sum, Target Sum, Word Break.
Same table, two loop orders. What does this print?
coins, amount = [1, 2, 5], 5
a = [1] + [0] * amount
for c in coins:
for t in range(c, amount + 1):
a[t] += a[t - c]
b = [1] + [0] * amount
for t in range(1, amount + 1):
for c in coins:
if c <= t:
b[t] += b[t - c]
print(a[amount], b[amount])Grid paths
When it applies: a grid where you move only right and down (or down a triangle), and you want the number of paths, the cheapest path, or the largest shape ending at each cell. Every cell's predecessors are above and to the left, so filling row by row always has the inputs ready. The state is dp[r][c]; usually one rolling row is enough.
Grid [[1,3,1],[1,5,1],[4,2,1]]. The start costs 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(m · n) time, O(n) space with a rolling row.
Best-known problems: Unique Paths, Minimum Path Sum, Maximal Square, Longest Increasing Path in a Matrix (moves go in all four directions there, so use memoised DFS instead of a row-by-row fill).
Two strings
When it applies: two strings (or arrays) and a question about matching them: common subsequence, edit distance, interleaving, counting embeddings, pattern matching. The state is dp[i][j] for the prefixes a[:i] and b[:j] (or suffixes). The recurrence always asks: do the last characters match? Add an extra row and column for the empty prefix; that is where the base cases live.
Row 0 and column 0 are the empty prefix: LCS 0.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(m · n) time, O(n) space with two rows.
Best-known problems: Longest Common Subsequence, Edit Distance, Distinct Subsequences, Regular Expression Matching.
Interval DP
When it applies: one sequence, and the answer for a range [i, j] is built from smaller ranges inside it: trim the ends (palindromes) or split at some k (Burst Balloons, matrix chain). The state is dp[i][j]. Fill by increasing length, or loop i downward and j upward, so inner ranges are ready first.
Length-1 ranges: every single character is a palindrome of length 1.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.Complexity: O(n²) when each range trims its ends, O(n³) when each range tries every split point k.
Best-known problems: Longest Palindromic Substring, Palindromic Substrings, Longest Palindromic Subsequence, Burst Balloons.
A decision checklist
Match each problem shape to its sub-pattern.
Put the steps for building a DP solution in order.
- Tap the steps below in the right order.
Traps
- Off-by-one in the table size. Prefix tables are length
n + 1because the empty prefix is a real state.ways[0] = 1(one way to make nothing) is the most common base case that people get wrong. - Wrong sweep direction in knapsack. Upward means reusable items; downward means each item once. Mixing them up silently gives the wrong answer on inputs like
[2, 6]for partition. - Wrong loop order when counting. Items outside counts combinations; totals outside counts orderings.
- Overwriting a value you still need. In a rolling row, save the old
dp[c]before overwriting if the next cell needs it as its diagonal (Maximal Square, Edit Distance). In a state machine, update all modes at once from yesterday's values. - Starting a max at 0 when answers can be negative (Maximum Product Subarray, Triangle). Start from the first element or negative infinity.
- Recursion depth. Top-down memoisation on a 10^4-long input can hit Python's default limit of 1000 frames. Bottom-up avoids it.
- Forgetting the modulo on counting problems, or applying it only at the end after the numbers overflowed (in languages with fixed-width integers).
Always test: the empty input (or length 1), all-equal values, an input where greedy fails, and the largest size from the constraints.
s from high to low for each item?How to talk it through
If you get stuck, say the brute-force recursion out loud. The arguments of that recursion are your state, and adding a memo turns it into DP. From there, converting to a bottom-up loop is mechanical.
- Overlapping subproblems
- A plain recursion would solve the same smaller problem many times. Caching each answer once is what makes DP fast.
- Optimal substructure
- The best answer to a problem is built from best answers to smaller versions of it.
- State
- What one cell of the DP table means, stated in one sentence, for example
best[i]is the most coins from houses0..i. - Recurrence
- The formula that computes a state from smaller states, such as
ways[i] = ways[i - 1] + ways[i - 2]. - Memoisation
- Top-down DP: recursion plus a cache keyed by the arguments.
- 0/1 vs unbounded knapsack
- Each item used at most once (sweep totals downward) versus any number of times (sweep upward).