Dynamic Programming
How to think (the 4-step recipe)
Section titled “How to think (the 4-step recipe)”Don’t try to “see” the table straight away. Go in this order and say each step out loud:
- State: “
dp[i]means ___.” Be precise. For example, “the max money robbing houses 0..i”. - Transition: “To get
dp[i], my last choice is either ___ or ___, sodp[i] = best of (...).” - Base case: the smallest inputs you can answer directly (
dp[0], an empty string, amount 0). - Answer: which cell holds the final answer? (
dp[n],dp[n-1], the max over alldp[i]?)
Then implement:
- Top-down (memoization): write the plain recursion first, then add a cache. This is the most natural path in an interview.
- Bottom-up (tabulation): fill the array in an order where dependencies are already computed. No recursion stack.
- Space optimization: if
dp[i]only needs the last 1–2 values, keep variables instead of an array.
Good thing to say: “Let me write the recursive brute force first. I can see f(i) gets recomputed, so I’ll memoize it. Then, if there’s time, I’ll convert it to bottom-up.”
Template
Section titled “Template”// Top-downInteger[] memo; // null = not computed (nicer than -1 sentinels)int solve(int i) { if (/* base case */ i < 0) return 0; if (memo[i] != null) return memo[i]; int result = /* combine solve(smaller) */ 0; return memo[i] = result;}
// Bottom-upint[] dp = new int[n + 1];dp[0] = /* base */ 0;for (int i = 1; i <= n; i++) { dp[i] = /* from dp[i-1], dp[i-2], ... */ 0;}return dp[n];Problem: Climbing Stairs (Easy) — LC 70
Approach (say out loud): “State: ways(i) = ways to reach step i. My last move was either 1 step or 2 steps, so ways(i) = ways(i-1) + ways(i-2). Base: ways(0) = 1, ways(1) = 1. It’s Fibonacci, and I only need the last two values.”
Java:
class Solution { public int climbStairs(int n) { int prev2 = 1, prev1 = 1; // ways(0), ways(1) for (int i = 2; i <= n; i++) { int cur = prev1 + prev2; prev2 = prev1; prev1 = cur; } return prev1; }}Complexity: O(n) time, O(1) space
Edge cases: n = 1 → 1, n = 2 → 2.
Problem: House Robber (Medium) — LC 198
Approach (say out loud): “State: dp[i] = the max money from houses 0..i. Choice at house i: skip it (dp[i-1]) or rob it (nums[i] + dp[i-2]). Take the max. Only two previous values are needed.”
Java:
class Solution { public int rob(int[] nums) { int prev2 = 0, prev1 = 0; // dp[i-2], dp[i-1] for (int x : nums) { int cur = Math.max(prev1, prev2 + x); prev2 = prev1; prev1 = cur; } return prev1; }}Complexity: O(n) time, O(1) space
Edge cases: a single house, two houses. House Robber II (LC 213, circular): answer = max(rob houses 0..n-2, rob houses 1..n-1).
Problem: Coin Change (Medium) — LC 322
Approach (say out loud): “Greedy fails (coins [1,3,4], amount 6: greedy gives 4+1+1, the best is 3+3). State: dp[a] = the min coins to make amount a. Transition: try every coin as the last coin, dp[a] = 1 + min(dp[a - coin]). Base: dp[0] = 0. I fill with a ‘infinity’ of amount+1.”
Java:
class Solution { public int coinChange(int[] coins, int amount) { int[] dp = new int[amount + 1]; Arrays.fill(dp, amount + 1); // acts as infinity dp[0] = 0; for (int a = 1; a <= amount; a++) { for (int coin : coins) { if (coin <= a) dp[a] = Math.min(dp[a], dp[a - coin] + 1); } } return dp[amount] > amount ? -1 : dp[amount]; }}Complexity: O(amount × coins) time, O(amount) space
Edge cases: amount = 0 → 0, impossible → -1. Use amount+1 instead of Integer.MAX_VALUE so +1 can’t overflow. Coin Change II (LC 518, count ways): loop over coins on the outside, dp[a] += dp[a - coin], with dp[0] = 1.
Problem: Longest Increasing Subsequence (Medium) — LC 300
Approach (say out loud): “State: dp[i] = the length of the LIS ending at i. For each j < i with nums[j] < nums[i], dp[i] = max(dp[i], dp[j] + 1). The answer is the max over all i. That’s O(n²). The follow-up is O(n log n) with patience sorting: keep tails, where tails[k] = the smallest tail of an increasing subsequence of length k+1, and binary search where each number goes.”
Java:
class Solution { // O(n^2) DP: explain this first public int lengthOfLIS(int[] nums) { int n = nums.length, best = 1; int[] dp = new int[n]; Arrays.fill(dp, 1); for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (nums[j] < nums[i]) dp[i] = Math.max(dp[i], dp[j] + 1); } best = Math.max(best, dp[i]); } return best; }
// O(n log n) follow-up public int lengthOfLISFast(int[] nums) { int[] tails = new int[nums.length]; int size = 0; for (int x : nums) { int lo = 0, hi = size; while (lo < hi) { // first index with tails[i] >= x int mid = lo + (hi - lo) / 2; if (tails[mid] >= x) hi = mid; else lo = mid + 1; } tails[lo] = x; if (lo == size) size++; } return size; }}Complexity: O(n²) or O(n log n) time, O(n) space
Edge cases: strictly increasing (LIS = n), duplicates (strictly increasing, so they don’t extend), a single element.
Problem: Unique Paths (Medium) — LC 62
Approach (say out loud): “State: dp[r][c] = the number of ways to reach that cell. I can only come from above or from the left, so dp[r][c] = dp[r-1][c] + dp[r][c-1]. The first row and column are all 1. I only need one row: row[c] += row[c-1].”
Java:
class Solution { public int uniquePaths(int m, int n) { int[] row = new int[n]; Arrays.fill(row, 1); for (int r = 1; r < m; r++) { for (int c = 1; c < n; c++) { row[c] += row[c - 1]; // row[c] (from above) + row[c-1] (from the left) } } return row[n - 1]; }}Complexity: O(m·n) time, O(n) space
Edge cases: m = 1 or n = 1 → 1. With obstacles (LC 63): set dp = 0 on obstacle cells.
Problem: Longest Common Subsequence (Medium) — LC 1143
Approach (say out loud): “State: dp[i][j] = the LCS of the first i chars of a and the first j chars of b. If the last chars match, dp[i-1][j-1] + 1. Otherwise, drop one char from either string: max(dp[i-1][j], dp[i][j-1]). I use an (m+1)×(n+1) table so row and column 0 are the empty-string base cases.”
Java:
class Solution { public int longestCommonSubsequence(String text1, String text2) { int m = text1.length(), n = text2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (text1.charAt(i - 1) == text2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); } } } return dp[m][n]; }}Complexity: O(m·n) time, O(m·n) space (can be reduced to O(n) with two rows)
Edge cases: an empty string → 0, no common characters → 0.
Problem: 0/1 Knapsack (classic, not on LC) / Partition Equal Subset Sum — LC 416
Approach (say out loud): “Each item is either taken once or not at all. State: dp[w] = the best value with capacity w. For each item, I loop w backwards from W down to its weight, so the item can’t be used twice in the same round: dp[w] = max(dp[w], dp[w - wt] + val). Partition Equal Subset Sum is the same thing with booleans: can I fill capacity sum/2?”
Java:
class Knapsack { // Classic 0/1 knapsack: max value within capacity W static int knapsack(int[] wt, int[] val, int W) { int[] dp = new int[W + 1]; for (int i = 0; i < wt.length; i++) { for (int w = W; w >= wt[i]; w--) { // BACKWARDS = each item at most once dp[w] = Math.max(dp[w], dp[w - wt[i]] + val[i]); } } return dp[W]; }}
class Solution { // LC 416: can nums be split into two equal-sum halves? public boolean canPartition(int[] nums) { int sum = 0; for (int x : nums) sum += x; if (sum % 2 != 0) return false; int target = sum / 2; boolean[] dp = new boolean[target + 1]; dp[0] = true; for (int x : nums) { for (int s = target; s >= x; s--) { dp[s] = dp[s] || dp[s - x]; } } return dp[target]; }}Complexity: O(n·W) time, O(W) space
Edge cases: odd total → false, an item heavier than the capacity (skipped by the loop bound). Loop forwards instead and you get unbounded knapsack (items reusable, like Coin Change).
Problem: Word Break (Medium) — LC 139
Approach (say out loud): “State: dp[i] = whether the prefix s[0..i) can be segmented. dp[i] is true if some j < i has dp[j] true and s[j..i) in the dictionary. Base: dp[0] = true (the empty prefix).”
Java:
class Solution { public boolean wordBreak(String s, List<String> wordDict) { Set<String> dict = new HashSet<>(wordDict); int n = s.length(); boolean[] dp = new boolean[n + 1]; dp[0] = true; for (int i = 1; i <= n; i++) { for (int j = 0; j < i; j++) { if (dp[j] && dict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[n]; }}Complexity: O(n³) time in the worst case (n² pairs × substring cost), O(n) space
Edge cases: words reused multiple times (allowed), no valid split.
Problem: Edit Distance (Medium) — LC 72 (brief)
Approach (say out loud): “State: dp[i][j] = the min operations to turn the first i chars of a into the first j chars of b. If the chars match, dp[i-1][j-1]. Otherwise 1 + min(insert dp[i][j-1], delete dp[i-1][j], replace dp[i-1][j-1]). Base: turning a string into an empty one takes i deletions, so dp[i][0] = i and dp[0][j] = j.”
Java:
class Solution { public int minDistance(String word1, String word2) { int m = word1.length(), n = word2.length(); int[][] dp = new int[m + 1][n + 1]; for (int i = 0; i <= m; i++) dp[i][0] = i; for (int j = 0; j <= n; j++) dp[0][j] = j; for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { if (word1.charAt(i - 1) == word2.charAt(j - 1)) { dp[i][j] = dp[i - 1][j - 1]; } else { dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])); } } } return dp[m][n]; }}Complexity: O(m·n) time and space
Edge cases: either string empty → the length of the other.
Quick reference: common DP shapes
Section titled “Quick reference: common DP shapes”| Shape | State | Examples |
|---|---|---|
| Linear, look back 1–2 | dp[i] |
Climbing stairs, house robber, decode ways |
| Linear, look back at all j < i | dp[i] |
LIS, word break |
| Target sum / capacity | dp[amount] |
Coin change, knapsack, partition |
| Two strings | dp[i][j] |
LCS, edit distance |
| Grid | dp[r][c] |
Unique paths, min path sum |
| Interval | dp[l][r] |
Longest palindromic substring, burst balloons (advanced) |