Dynamic programming
Go from recursion to memoisation to tabulation on 1D and 2D problems.
By Invicly Tech, , in Interview Preparation. About 13 minutes to read.
In short
Dynamic programming solves problems with overlapping subproblems by storing each answer once. You define a state, write how it depends on smaller states, then compute with memoisation or a table.
Explained simply
Dynamic programming (DP) sounds scary, but the idea is simple: never solve the same small problem twice. Write down each answer the first time you work it out, and look it up the next time you need it.
Picture climbing stairs where you may take 1 or 2 steps at a time. The number of ways to reach step 10 is the ways to reach step 9 plus the ways to reach step 8. A plain recursive solution recomputes step 8, step 7 and so on again and again. Remembering them turns an exponential amount of work into about 10 additions.
DP needs two ingredients. First, the big answer must be built from answers to smaller versions of the same question. Second, those smaller questions must repeat. Most "count the ways", "minimum cost" and "maximum value" problems have both.
There are two ways to write it. Top-down (memoisation) is your recursive solution plus a cache. Bottom-up (tabulation) fills a table in a loop, starting from the smallest cases. Both give the same answers; pick whichever you find easier to get right, then improve it if asked.
Press Play on a diagram to walk through it one step at a time.
- 1Define the state
dp[a] = fewest coins to make amount a
- 2Write the transition
dp[a] = min over coins of dp[a - c] + 1
- 3Set base cases
dp[0] = 0
- 4Memoise
Cache recursive results to avoid repeats
- 5Tabulate
Fill the table bottom-up in dependency order
- 6Optimise space
Keep only rows or values still needed
- Recursion plus a cache
- Computes only needed states
- Easy to derive from brute force
- Recursion depth limits
- Loops fill a table
- Computes all states in order
- No recursion overhead
- Easier to optimise space
- fib(4)
- fib(3), computed once here
- fib(2)
- fib(3), computed again
- fib(2), computed again
- fib(1)
In depth
Finding the state: what must I know to continue?
The state is the smallest set of facts that fully describes a subproblem. Ask: "if I stopped halfway, what would I need to write down to finish later?" In House Robber, you only need the index of the next house, so the state is i. In Longest Common Subsequence (LCS), you need a position in each string, so the state is (i, j). In 0/1 knapsack, you need the item index and the remaining capacity.
The state decides the cost. Time is the number of states times the work per state. LCS has m x n states and does O(1) work for each, so it is O(m x n). If your state has too many parts, the table explodes; look for a part you can drop.
- State: what you must remember
- Transition: how a state uses smaller states
- Base case: states you know without work
- Answer: which state holds the final result
One problem, three versions: House Robber
You cannot rob two neighbouring houses. Let best(i) be the most money from the first i houses. For the last house you either skip it, giving best(i - 1), or rob it, giving best(i - 2) + nums[i - 1]. Take the larger.
Written as plain recursion, this branches twice per call and costs O(2^n). Add a cache (memoisation) and each of the n states is solved once: O(n) time and O(n) space. Then notice that each state only uses the two before it, so a loop with two variables gives O(n) time and O(1) space. Interviewers often ask for exactly this progression, so practise walking through all three out loud.
- Two calls per call
- Recomputes the same houses
- O(2^n) time
- Same recursion plus a cache
- Each i solved once
- O(n) time, O(n) space
- Loop from the first house
- Keep only best(i - 1) and best(i - 2)
- O(n) time, O(1) space
2D DP on two strings or a grid
For two strings a and b, let dp[i][j] be the answer for the first i characters of a and the first j characters of b. Give the table an extra row and column for empty prefixes, so dp[0][j] and dp[i][0] are base cases and you never index outside the strings.
In LCS, if the last characters match, dp[i][j] = dp[i - 1][j - 1] + 1. If not, drop one character from either string and keep the better result: max(dp[i - 1][j], dp[i][j - 1]). Fill the table row by row, left to right, so every cell you read is already done. Unique Paths works the same way on a grid: paths to a cell equal paths from above plus paths from the left. When a row only reads the previous row, you can keep two rows and cut space to O(n).
- 1Compare characters
a[i - 1] versus b[j - 1]
- 2Equal
dp[i - 1][j - 1] + 1, the diagonal plus one
- 3Different
max(dp[i - 1][j], dp[i][j - 1]), above or left
- 4Move on
Next cell to the right, then the next row
- 5Answer
dp[m][n], the bottom-right cell
The knapsack family and loop direction
In 0/1 knapsack each item can be used once. With a one-dimensional array dp[c] (best value with capacity c), loop over items, and for each item loop capacity downward from the maximum to the item's weight. Going downward means dp[c - w] still holds the value from before this item, so the item cannot be counted twice.
In unbounded problems like Coin Change, a coin can be reused, so loop the amount upward: dp[a - c] may already include this coin, which is exactly what you want. For counting, loop order matters too. In Coin Change II, putting coins in the outer loop counts combinations (1 + 2 equals 2 + 1). Putting amounts in the outer loop counts ordered sequences, which is a different problem (Combination Sum IV).
- 0/1 knapsack: capacity loop goes down
- Unbounded: amount loop goes up
- Coins outer: combinations
- Amount outer: ordered sequences
Patterns worth recognising
Most interview DP problems fall into a few families, and knowing them makes the state obvious. Linear problems use dp[i] over a single array: Climbing Stairs, House Robber, Decode Ways, Word Break. Grid problems use dp[r][c]: Unique Paths, Minimum Path Sum. Two-sequence problems use dp[i][j]: LCS, Edit Distance. Knapsack problems use (item, capacity): Partition Equal Subset Sum, Coin Change, Target Sum. Interval problems use dp[l][r] over a range: Longest Palindromic Substring, Burst Balloons.
Longest Increasing Subsequence deserves its own note. The simple DP is O(n^2): for each i, look at every earlier j with a smaller value. There is also an O(n log n) method that keeps the smallest possible tail for each length and binary searches it. Know both and mention the faster one.
Learn it in 6 short steps
About 2h each. Track them with a timer in your plan.
- 1Identify states and transitions~2h
- 2Convert recursion to memoisation~2h
- 3Convert memoisation to tabulation~2h
- 4Solve 1D problems: Climbing Stairs, House Robber~2h
- 5Solve 2D problems: LCS, Unique Paths~2h
- 6Practice knapsack and Coin Change~2h
Key points
- Complexity is the number of states times the work per state.
- Coin Change is O(amount x coins) time and O(amount) space.
- 2D problems like LCS and Unique Paths use a grid indexed by two positions.
- If brute-force recursion recomputes the same arguments, DP probably applies.
Key terms
Tap a card to flip it. 0/5 known
Examples
from functools import cache
@cache
def climb(n): # Climbing Stairs, memoised
return 1 if n <= 1 else climb(n - 1) + climb(n - 2)
def coin_change(coins, amount): # tabulation
INF = amount + 1
dp = [0] + [INF] * amount # dp[a] = fewest coins for a
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 -1House Robber: [2, 7, 9, 3, 1]
Keep two numbers: prev2 (best up to two houses back) and prev1 (best up to the last house), both 0 at the start. House 2: max(0, 0 + 2) = 2. House 7: max(2, 0 + 7) = 7. House 9: max(7, 2 + 9) = 11. House 3: max(11, 7 + 3) = 11. House 1: max(11, 11 + 1) = 12. The answer is 12: rob the houses with 2, 9 and 1. O(n) time, O(1) space.
int rob(int[] nums) {
int prev2 = 0, prev1 = 0; // best two back, best one back
for (int x : nums) {
int cur = Math.max(prev1, prev2 + x); // skip this house, or rob it
prev2 = prev1;
prev1 = cur;
}
return prev1;
}Longest Common Subsequence of "abcde" and "ace"
A subsequence keeps the order but may skip characters. Build a 6 x 4 table with row 0 and column 0 set to 0 for empty prefixes. Matching a with a gives 1 on the diagonal. Later, c matches c, so that cell is the diagonal value 1 plus 1, which is 2. Finally e matches e, giving 3. Cells where characters differ copy the larger of the cell above and the cell to the left. The bottom-right cell holds 3, for the subsequence "ace".
int longestCommonSubsequence(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1]; // row 0 and column 0: empty prefix
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
? dp[i - 1][j - 1] + 1
: Math.max(dp[i - 1][j], dp[i][j - 1]);
return dp[m][n]; // O(m x n) time and space
}Quick reference
- Time = number of states x work per state; space = the part of the table you keep
- 0/1 knapsack in a 1D array: loop capacity downward so each item is used once
- Unbounded (Coin Change): loop the amount upward so a coin can be reused
- Count combinations: coins in the outer loop; count orderings: amount in the outer loop
- String DP: add an empty-prefix row and column to avoid edge checks
- If dp[i] needs only dp[i - 1] and dp[i - 2], keep two variables for O(1) space
- LIS: O(n^2) DP, or O(n log n) by binary searching the smallest tails
- Python memo: @functools.cache; deep recursion may need sys.setrecursionlimit
Common mistakes
- Starting to code before writing the state and transition in words.
- Wrong base cases, such as dp[0] = 1 when counting minimum coins.
- Filling the table in an order where dependencies are not yet computed.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Min Cost Climbing Stairs: cost[i] is paid when you step on stair i, you may climb 1 or 2 stairs, and you may start on stair 0 or 1. Return the cheapest cost to reach the top (just past the last stair).
- Exercise 2medium
Coin Change II: count the combinations of coins that make up an amount. Coins can be reused.
- Exercise 3hard
Edit Distance: the fewest inserts, deletes and replacements to turn word a into word b.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I get better at dynamic programming?
- Learn the families (linear, grid, two strings, knapsack, intervals) and solve three or four problems in each. For every problem, write the state and the transition in plain words before writing any code.
- Should I use top-down or bottom-up in an interview?
- Top-down is usually faster to write correctly because it follows the recursion you already found. If the interviewer asks for better space or worries about recursion depth, convert it to a table and then shrink the table.
- What is the difference between DP and divide and conquer?
- Both split a problem into smaller ones. In divide and conquer, like merge sort, the pieces do not overlap, so there is nothing to reuse. DP is for when the same pieces come up again and again.