Dynamic Programming, Part 2: The Classic Problems
After this lesson, you will be able to:
- Solve coin change, 0/1 knapsack, LCS, LIS and edit distance with the 5-question framework
- Read and fill a 2D DP table, and reconstruct the answer path from it
- Shrink a 2D table down to one or two rows, and know when the reverse loop is required
- Choose between memoization and tabulation from the size of the problem rather than by habit
Before you start
#Classic DP Problems
Each problem starts with the question in plain words, then the five answers, then the code. Before you read the code, try to give the five answers yourself.
#Problem 1: Coin Change: Minimum Coins
You have coins of certain values and an amount to pay. What is the fewest coins that add up to exactly that amount? Always taking the biggest coin can fail. With coins 1, 3 and 4 and an amount of 6, the biggest-first choice gives 4 + 1 + 1 (three coins), but 3 + 3 uses two. DP checks every option.
def coin_change(coins: list[int], amount: int) -> int:
"""Find the minimum number of coins needed to make 'amount'.
1. STATE: dp[i] = minimum coins needed to make amount i
2. RECURRENCE: dp[i] = min(dp[i - coin] + 1) for each coin <= i
(use one coin of this denomination, then solve for the remainder)
3. BASE CASE: dp[0] = 0 (0 coins needed to make amount 0)
4. ORDER: left to right, i from 1 to amount
5. ANSWER: dp[amount] if < infinity, else -1 (not achievable)
Time: O(amount * len(coins)), Space: O(amount)
"""
INF = float("inf")
dp = [INF] * (amount + 1)
dp[0] = 0 # base case
for i in range(1, amount + 1):
for coin in coins:
if coin <= i and dp[i - coin] + 1 < dp[i]:
dp[i] = dp[i - coin] + 1
return dp[amount] if dp[amount] != INF else -1
print(coin_change([1, 5, 10, 25], 36)) # 3 (25 + 10 + 1)
print(coin_change([2], 3)) # -1 (impossible with only coin=2)
print(coin_change([1, 2, 5], 11)) # 3 (5 + 5 + 1)#Problem 2: Longest Common Subsequence (LCS)
git diff finds the lines two files share.The table has one row for each character of the first string and one column for each character of the second. The cell at row i, column j answers one question: what is the LCS of the first i characters of one string and the first j of the other?
Each cell is built from cells that are already filled. If the two characters match, take the cell diagonally up and to the left and add 1. If they do not match, take the larger of the cell above and the cell to the left. That is why the table is filled row by row, left to right: everything a cell needs is already there.
def lcs(s1: str, s2: str) -> int:
"""Find the length of the longest common subsequence.
A subsequence is a sequence that can be derived from another sequence by
deleting some (or no) characters without changing the order of the remaining.
e.g., LCS("ABCBDAB", "BDCAB") = 4 ("BCAB" or "BDAB")
1. STATE: dp[i][j] = LCS length of s1[:i] and s2[:j]
2. RECURRENCE:
if s1[i-1] == s2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 (characters match)
else: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) (skip one character)
3. BASE CASES: dp[0][j] = 0, dp[i][0] = 0 (empty string has LCS = 0)
4. ORDER: row by row, left to right
5. ANSWER: dp[m][n]
Time: O(m * n), Space: O(m * n)
"""
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i - 1] == s2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
def lcs_with_string(s1: str, s2: str) -> str:
"""Return the actual LCS string by backtracking through the DP table."""
m, n = len(s1), len(s2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
# Backtrack
result = []
i, j = m, n
while i > 0 and j > 0:
if s1[i-1] == s2[j-1]:
result.append(s1[i-1])
i -= 1; j -= 1
elif dp[i-1][j] > dp[i][j-1]:
i -= 1
else:
j -= 1
return "".join(reversed(result))
print(lcs("ABCBDAB", "BDCAB")) # 4
print(lcs_with_string("ABCBDAB", "BDCAB")) # BDAB
print(lcs("intention", "execution")) # 5`lcs` returns only a length. Getting the actual string needs a second pass that walks the finished table backwards from dp[m][n]. Why can the forward pass not just build the string as it goes?
#Problem 3: 0/1 Knapsack
def knapsack_01(weights: list[int], values: list[int],
capacity: int) -> int:
"""Classic 0/1 Knapsack: maximize value within weight capacity.
Each item can be taken at most once (0 or 1 times).
1. STATE: dp[i][w] = max value using first i items with capacity w
2. RECURRENCE:
if weights[i-1] <= w:
dp[i][w] = max(dp[i-1][w], # skip item i
dp[i-1][w - weights[i-1]] + values[i-1]) # take item i
else:
dp[i][w] = dp[i-1][w] # item too heavy, must skip
3. BASE CASES: dp[0][w] = 0 for all w (no items = no value)
4. ORDER: row by row (outer = items, inner = capacity)
5. ANSWER: dp[n][capacity]
Time: O(n * capacity), Space: O(n * capacity)
"""
n = len(weights)
dp = [[0] * (capacity + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for w in range(capacity + 1):
# Option 1: skip item i
dp[i][w] = dp[i - 1][w]
# Option 2: take item i (if it fits)
if weights[i - 1] <= w:
dp[i][w] = max(dp[i][w],
dp[i - 1][w - weights[i - 1]] + values[i - 1])
return dp[n][capacity]
# 4 items, capacity = 5
weights = [2, 3, 4, 5]
values = [3, 4, 5, 6]
print(knapsack_01(weights, values, 5)) # 7 (items 0 and 1: weight 2+3=5, value 3+4=7)
print(knapsack_01(weights, values, 8)) # 10 (items 1 and 3: weight 3+5=8, value 4+6=10)#Problem 4: Longest Increasing Subsequence (LIS)
[10, 9, 2, 5, 3, 7, 101, 18], the values 2, 3, 7, 18 go up and keep their order. The state is the length of the best increasing subsequence that ends at each position.def lis_dp(nums: list[int]) -> int:
"""Longest Increasing Subsequence. O(n²) DP approach.
1. STATE: dp[i] = length of LIS ending at index i
2. RECURRENCE: dp[i] = max(dp[j] + 1) for all j < i where nums[j] < nums[i]
3. BASE CASE: dp[i] = 1 for all i (each element is an LIS of length 1)
4. ORDER: left to right
5. ANSWER: max(dp)
"""
if not nums:
return 0
n = len(nums)
dp = [1] * n # base case: every element alone is an LIS of length 1
for i in range(1, n):
for j in range(i):
if nums[j] < nums[i]: # nums[j] can extend the sequence
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)
import bisect
def lis_binary_search(nums: list[int]) -> int:
"""LIS in O(n log n) using binary search (patience sorting).
Maintain a 'tails' array: tails[k] = the smallest tail element
of all increasing subsequences of length k+1.
"""
tails: list[int] = []
for num in nums:
pos = bisect.bisect_left(tails, num)
if pos == len(tails):
tails.append(num) # extend the longest subsequence
else:
tails[pos] = num # replace to maintain smallest tails
return len(tails)
seq = [10, 9, 2, 5, 3, 7, 101, 18]
print(f"LIS (O(n²)): {lis_dp(seq)}") # 4 (2,3,7,18 or 2,5,7,18)
print(f"LIS (O(n log n)): {lis_binary_search(seq)}") # 4lis_binary_search returns len(tails), never tails itself. Run it on [1, 5, 6, 2] and tails ends as [1, 2, 6]. Is that an increasing subsequence of the input?
#Problem 5: Edit Distance (Levenshtein)
How many single-letter changes does it take to turn one word into another? A change is one of three moves: insert a letter, delete a letter, or replace a letter. "kitten" becomes "sitting" in 3 moves. The cell at row i, column j holds the answer for the first i letters of one word and the first j letters of the other.
def edit_distance(word1: str, word2: str) -> int:
"""Minimum edit operations (insert, delete, replace) to transform word1 → word2.
Used in: spell checkers, diff tools, DNA alignment, NLP similarity metrics.
1. STATE: dp[i][j] = min edits to transform word1[:i] into word2[:j]
2. RECURRENCE:
if word1[i-1] == word2[j-1]: dp[i][j] = dp[i-1][j-1] (no operation needed)
else: dp[i][j] = 1 + min(
dp[i-1][j], # delete from word1
dp[i][j-1], # insert into word1
dp[i-1][j-1] # replace in word1
)
3. BASE CASES:
dp[0][j] = j (transform empty string to word2[:j] requires j insertions)
dp[i][0] = i (transform word1[:i] to empty string requires i deletions)
4. ORDER: row by row
5. ANSWER: dp[m][n]
Time: O(m * n), Space: O(m * n) [reducible to O(min(m,n)) with rolling row]
"""
m, n = len(word1), len(word2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i # delete all of word1[:i]
for j in range(n + 1):
dp[0][j] = j # insert all of word2[:j]
for i in range(1, m + 1):
for j in range(1, n + 1):
if word1[i - 1] == word2[j - 1]:
dp[i][j] = dp[i - 1][j - 1] # characters match — free
else:
dp[i][j] = 1 + min(
dp[i - 1][j], # delete word1[i-1]
dp[i][j - 1], # insert word2[j-1]
dp[i - 1][j - 1], # replace word1[i-1] with word2[j-1]
)
return dp[m][n]
print(edit_distance("kitten", "sitting")) # 3
# kitten → sitten (replace k→s)
# sitten → sittin (replace e→i)
# sittin → sitting (insert g)
print(edit_distance("intention", "execution")) # 5
print(edit_distance("", "abc")) # 3 (insert a, b, c)
print(edit_distance("abc", "abc")) # 0 (already equal)In the edit-distance table, the base cases are dp[i][0] = i and dp[0][j] = j. Why are they not both 0?
#Memoization vs Tabulation Comparison
The recursion-dp lesson explains the two styles. Here are only the points that matter for the problems above.
| Memoization (top-down) | Tabulation (bottom-up) | |
|---|---|---|
| States visited | Only the ones the answer needs | All of them |
| Deep tables | Recursion depth can pass the limit of about 1000 | A loop, so no limit |
| Saving memory | Hard, because the cache keeps every answer | Easy, because you can keep only the rows still needed |
| Writing it | Close to the recurrence | You must choose the fill order |
import functools
# Same problem, both styles side by side: Coin Change
# --- Top-Down (Memoization) ---
@functools.cache
def coin_change_memo(coins_tuple: tuple[int, ...], amount: int) -> int:
if amount == 0:
return 0
if amount < 0:
return float("inf")
return 1 + min(coin_change_memo(coins_tuple, amount - c) for c in coins_tuple)
coins = (1, 5, 10, 25)
result = coin_change_memo(coins, 36)
print(f"Memo result: {result}") # 3
# --- Bottom-Up (Tabulation) ---
def coin_change_tab(coins: list[int], amount: int) -> int:
dp = [float("inf")] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for c in coins:
if c <= i:
dp[i] = min(dp[i], dp[i - c] + 1)
return dp[amount] if dp[amount] != float("inf") else -1
print(f"Tab result: {coin_change_tab([1, 5, 10, 25], 36)}") # 3When only a small part of the table can ever be reached, memoization does less work. When almost every state is needed, or the table is deep, use tabulation. The coin-change question below shows both cases.
Both styles solve coin change with the same recurrence. The coins are [1, 5, 10, 25] and the amount is 3000. Which style would you reach for, and why?
#Code Playground: DP Problems
Tests: Solve Climbing Stairs, Coin Change, Edit Distance and LCS using dynamic programming.
#Key Takeaways
- Coin change, knapsack, LCS, LIS and edit distance are one technique used five times: state, recurrence, base cases, fill order, answer. The framework is the same every time. Only the recurrence changes.
- Memoization and tabulation cost about the same time. Memoization only visits the states it needs. Tabulation avoids the recursion limit and is easier to shrink.
- A 2D table also stores the path, not just the score. Walking back through it rebuilds which letters matched or which edits were chosen.
- When a row depends only on the row above it, keep two rows. For 0/1 knapsack, run the inner loop backwards so an item is not counted twice.
- The knapsack cost O(n * capacity) is pseudo-polynomial: it grows with the value of the capacity, not the length of its written form.
- Not every array problem is a DP problem. For two pointers, sliding windows and prefix sums, see Array Patterns.
Coins are 1, 3 and 4, and the amount is 6. What does the tabulation from the lesson give, and why does taking the biggest coin first fail?