2D Dynamic Programming
Data Structures & Algorithms · Greedy & Dynamic Programming · Advanced · 30 min
Solve grid and two-string problems (unique paths, minimum path sum, LCS, edit distance) by defining dp[i][j] in one sentence and filling a table.
A spreadsheet where every cell is computed only from the cell above, the cell to the left and the cell diagonally up-left, filling from the top-left corner to the bottom-right.
The idea in everyday words
Imagine walking through a city grid, only ever going right or down. How many routes reach a corner? You only need two numbers: the routes into the corner just above, and the routes into the corner just to the left. Write each answer on the map once, and every later corner just reads it. You never re-walk old streets.
When one index is not enough
In 1D DP (climbing stairs, house robber) the state is one number: "the answer for the first i items". Some problems have two things that change:
- a grid: the row and the column,
- two strings: how much of word A and how much of word B we have used.
So the state is dp[i][j], a table. Use this 5-step recipe every time:
- State. Say what
dp[i][j]means in one sentence. ("Fewest edits to turn the first i letters of a into the first j letters of b.") - Base cases. Usually row 0 and column 0 (an empty prefix or the grid's edge).
- Transition. Which neighbours does a cell read? Usually up
[i-1][j], left[i][j-1], diagonal[i-1][j-1]. - Fill order. Make sure those neighbours are ready first: row by row, left to right.
- Answer. Usually the bottom-right cell
dp[m][n].
The one-sentence state is the hard part. Once it is right, the transition almost writes itself.
Grid paths: unique paths and minimum path sum
Unique paths: a robot in an r × c grid moves only right or down. How many routes from top-left to bottom-right?
The last move into a cell came 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 (only one straight route).
| c0 | c1 | c2 | |
|---|---|---|---|
| r0 | 1 | 1 | 1 |
| r1 | 1 | 2 | 3 |
| r2 | 1 | 3 | 6 |
Minimum path sum: each cell has a cost; find the cheapest route. Same shape, but min instead of +: dp[r][c] = grid[r][c] + min(up, left).
def unique_paths(rows, cols):
dp = [[1] * cols for _ in range(rows)]
for r in range(1, rows):
for c in range(1, cols):
dp[r][c] = dp[r - 1][c] + dp[r][c - 1]
return dp[-1][-1]
def min_path_sum(grid):
rows, cols = len(grid), len(grid[0])
dp = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
if r == 0 and c == 0:
dp[r][c] = grid[0][0]
elif r == 0:
dp[r][c] = dp[r][c - 1] + grid[r][c]
elif c == 0:
dp[r][c] = dp[r - 1][c] + grid[r][c]
else:
dp[r][c] = grid[r][c] + min(dp[r - 1][c], dp[r][c - 1])
return dp[-1][-1]
print(unique_paths(3, 3)) # 6
print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7
Longest common subsequence (LCS)
A subsequence keeps the order but may skip letters: "ACE" is a subsequence of "ABCDE". The LCS of two words is the longest subsequence they share.
State: dp[i][j] = LCS length of the first i letters of a and the first j letters of b. Row 0 and column 0 are 0 (an empty word shares nothing).
Transition: look at the last letters, a[i-1] and b[j-1].
- They match: use that letter.
dp[i][j] = dp[i-1][j-1] + 1(diagonal + 1). - They differ: they cannot both be the last letter of the answer, so drop one of them and keep the better result:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])(up or left).
def lcs(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[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]
print(lcs("abcde", "ace")) # 3
print(lcs("ABCBDA", "BDCABA")) # 4
Why the extra row and column (size m+1 by n+1)? They stand for the empty prefix, so the base case needs no special if-statements.
Edit distance
How many single-letter edits (insert, delete, replace) turn word a into word b? Spell-checkers and DNA tools use this.
State: dp[i][j] = fewest edits to turn the first i letters of a into the first j letters of b.
Base cases: dp[i][0] = i (delete all i letters) and dp[0][j] = j (insert all j letters).
Transition: look at the last letters.
- Equal: nothing to fix,
dp[i][j] = dp[i-1][j-1]. - Different: try each fix for the last letter and pay 1:
- replace a's last letter with b's:
dp[i-1][j-1] + 1(diagonal) - delete a's last letter:
dp[i-1][j] + 1(up) - insert b's last letter at the end:
dp[i][j-1] + 1(left) - take the minimum.
- replace a's last letter with b's:
Example: "horse" → "ros" takes 3 edits: replace h with r (rorse), delete r (rose), delete e (ros).
Pattern to remember: in two-string DP, diagonal = use both letters, up = drop a letter of a, left = drop a letter of b.
Saving memory, and reading the answer back
Each row only reads the row above and itself. So you can keep just two rows (or one row plus a variable for the diagonal) and cut memory from O(m·n) to O(n).
def lcs_two_rows(a, b):
prev = [0] * (len(b) + 1)
for i in range(1, len(a) + 1):
cur = [0] * (len(b) + 1)
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
cur[j] = prev[j - 1] + 1
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur
return prev[-1]
print(lcs_two_rows("abcde", "ace")) # 3
The trade-off: if you also need the actual subsequence or the list of edits, keep the full table and walk back from the bottom-right corner, following the neighbour each value came from. The "See it" visual does exactly that at the end.
Step by step
- Define the state:
Edit distance from "cat" to "cut". dp[i][j] = fewest edits to turn the first i letters of "cat" into the first j letters of "cut". The table is 4 × 4.
- Base cases:
Row 0 is 0, 1, 2, 3 (insert that many letters). Column 0 is 0, 1, 2, 3 (delete that many letters).
- dp[1][1]: 'c' vs 'c':
Equal, so copy the diagonal dp[0][0] = 0. Turning "c" into "c" is free.
- dp[2][2]: 'a' vs 'u':
Different. Replace: dp[1][1] + 1 = 1. Delete: dp[1][2] + 1 = 2. Insert: dp[2][1] + 1 = 2. Minimum is 1 (replace a with u).
- dp[3][3]: 't' vs 't':
Equal, so copy the diagonal dp[2][2] = 1.
- Answer:
dp[3][3] = 1. One edit: replace 'a' with 'u'. 9 inner cells, each O(1) work.
Code example
def edit_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i # delete everything
for j in range(n + 1):
dp[0][j] = j # insert everything
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1], # replace
dp[i - 1][j], # delete
dp[i][j - 1]) # insert
for row in dp:
print(row)
return dp[m][n]
print("edit distance:", edit_distance("horse", "ros"))Complexity
- Time: O(m·n): one cell per pair of prefixes, O(1) work per cell
- Space: O(m·n) for the full table, or O(n) keeping only the previous row when you need just the number
Interview tips
Say the state sentence before coding; interviewers often stop you there if it is wrong, which saves time.
Start from the recursive brute force, point out the repeated (i, j) pairs, then convert to a table. That story shows real understanding.
Offer the space optimisation (two rows) as a follow-up, and mention that you lose the ability to reconstruct the path.
Classic family: Unique Paths, Minimum Path Sum, LCS, Edit Distance, Longest Palindromic Subsequence, Interleaving String.
Challenge: Edit Distance
Return the minimum number of operations to turn word1 into word2. Allowed operations on single letters: insert, delete, replace.
Aim for O(m · n) with a table (or a memo). Plain recursion with no memo is too slow for one of the tests.
Example: edit_distance("horse", "ros") → 3 (horse → rorse → rose → ros)
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Unique Paths (Medium)
- Minimum Path Sum (Medium)
- Longest Common Subsequence (Medium)
- Edit Distance (Medium)
More in Greedy & Dynamic Programming
Previous: Dynamic Programming · Next: Knapsack, Subset Sum & Coin Change