2D DP: grids & two sequences
Define 2D states and fill grid and string DP tables in the right order.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
Two-dimensional DP uses states with two indexes, such as a grid cell or a position in each of two strings. Each cell depends on a few neighbours, usually above, left or diagonal, so the table is filled row by row. Edit distance and grid path counting are the classic examples.
Explained simply
Some problems need two numbers to describe where you are. On a grid, it is the row and the column. When comparing two words, it is how far you are in the first word and how far in the second. A DP with two numbers in its state is called 2D DP, and its memory is a table.
Each cell of the table is the answer to one small problem. For a grid, cell (r, c) might hold the number of ways to walk from the top-left corner to that cell. For two words, cell (i, j) might hold how many edits turn the first i letters of one word into the first j letters of the other.
Every cell is built from a few nearby cells that were filled earlier, usually the one above, the one to the left, and the one diagonally above-left. So you fill the table row by row, left to right, and the answer sits in the bottom-right corner.
Tables can get big. A 10,000 by 10,000 table has 100 million cells, too much memory for Python. The good news is that most of these problems only look at the previous row, so you can keep just one or two rows.
Press Play on a diagram to walk through it one step at a time.
- Characters match
- dp[i-1][j-1]
- Replace
- 1 + dp[i-1][j-1]
- Delete from a
- 1 + dp[i-1][j]
- Insert into a
- 1 + dp[i][j-1]
- Step 1Row 0
1, 1, 1: only one way along the top
- Step 2Row 1
1, 2, 3: each cell = up + left
- Step 3Row 2
1, 3, 6
- Step 4Answer
6 = C(4, 2)
In depth
Two kinds of 2D state
Grid DP: dp[r][c] describes the cell at row r, column c. Moves are limited (often only right and down), so each cell depends on its neighbours above and to the left. This is why grid DP needs a restriction on moves: if you could move in all four directions, cells would depend on each other in a loop, and you would need a graph algorithm such as BFS or Dijkstra instead.
Two-sequence DP: dp[i][j] describes the prefixes a[:i] and b[:j]. The table has (m + 1) x (n + 1) cells, because row 0 and column 0 stand for empty prefixes. Those base cases are usually easy: turning an empty word into j letters takes j insertions. Shifting by one keeps string index i - 1 paired with table index i, which is where most off-by-one bugs live.
- Grid: dp[r][c] from up and left
- Strings: dp[i][j] over prefixes, size (m + 1) x (n + 1)
- Four-way moves create cycles: use a graph algorithm
Choosing the fill order
Draw an arrow from each cell to the cells it reads. The fill order must visit the cells at the tail of each arrow first. If cells read up, left and up-left, plain row-major order (outer loop rows, inner loop columns) works. If a recurrence reads down and right, as when the state means "from (r, c) to the bottom-right corner", loop rows and columns backwards.
Some problems read only the diagonal, such as interval problems where dp[i][j] needs dp[i + 1][j - 1]. Then you fill by the length j - i, or with i descending and j ascending. When in doubt, top-down memoisation sidesteps the question, because the recursion computes dependencies on demand.
- Unique paths, edit distance, LCS
- Rows 0 to m, columns 0 to n
- Answer at dp[m][n]
- Dungeon game, paths to the corner
- Rows m-1 down to 0, columns backwards
- Answer at dp[0][0]
- Palindromes, matrix chain
- Loop by length j - i
- Answer at dp[0][n-1]
Rolling rows without bugs
If row r only needs row r - 1, keep one list. For unique paths it is beautifully short: start with row = [1] * n, then for each new row do row[c] += row[c - 1] for c from 1. Before the update, row[c] still holds the cell above; row[c - 1] already holds the cell to the left. Space becomes O(n).
Edit distance also reads the diagonal dp[i - 1][j - 1], which the one-row version overwrites one step earlier. Save it in a variable, often called prev or diag, before overwriting each cell. Pick the shorter string for the columns to get O(min(m, n)) space. You lose the ability to trace back the actual edits, so keep the full table when you need them.
- Step 1Save diag
tmp = row[j], the old up value.
- Step 2Read neighbours
Up = row[j], left = row[j - 1], diag = prev.
- Step 3Write
row[j] = prev if match, else 1 + min of the three.
- Step 4Shift
prev = tmp for the next column.
Grids with obstacles, costs and maths
Obstacles are a small change: a blocked cell gets 0 ways, and the rest of the recurrence stays the same. Watch the first row and column: a single obstacle there blocks every cell after it in that line. Minimum path sum replaces + with min: dp[r][c] = grid[r][c] + min(up, left).
Without obstacles, unique paths has a closed form. Every route makes exactly m - 1 down moves and n - 1 right moves in some order, so the count is the binomial coefficient C(m + n - 2, m - 1). For a 3 x 7 grid that is C(8, 2) = 28, and Python's math.comb(8, 2) computes it directly. The DP is still worth knowing because the formula breaks as soon as obstacles or costs appear.
Where these tables are used
Edit distance (also called Levenshtein distance) powers spell checkers and "did you mean" suggestions. Fuzzy search libraries compute it, often with a cut-off to stop early when the distance is already too large. Sequence alignment in biology (Needleman-Wunsch) is the same table with costs for matches, mismatches and gaps.
Text diff tools compare two files line by line with the same idea. git diff uses the Myers algorithm by default, a cleverer method that runs in O((m + n) D) time, where D is the size of the difference, so it is very fast when two files are nearly the same.
Learn it in 5 short steps
About 50m each. Track them with a timer in your plan.
- 1Count unique grid paths~50m
- 2Find minimum path sum~50m
- 3Compute edit distance~50m
- 4Choose table fill order~50m
- 5Reduce a 2D table to one row~50m
Key points
- Edit distance: O(m x n) time and space, O(min(m, n)) space with rolling rows.
- Unique paths: dp[r][c] = dp[r-1][c] + dp[r][c-1].
- Extra row and column of base cases simplify empty-prefix handling.
- Fill order must guarantee every dependency is computed first.
Key terms
Tap a card to flip it. 0/3 known
Examples
def edit_distance(a, b): # O(m * n)
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
for j in range(n + 1): dp[0][j] = j
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], dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
print(edit_distance('horse', 'ros')) # 3Minimum path sum with one row
Grid [[1, 2, 3], [4, 5, 6]], moves only right or down. We want the cheapest total from top-left to bottom-right. Step 1: the first row is a running sum: 1, 3, 6. Step 2: for the second row, the first cell can only come from above: 1 + 4 = 5. Then 5 + min(3, 5) = 8, and 6 + min(6, 8) = 12. The answer is 12, along 1, 2, 3, 6. Only one list of length n is kept.
def min_path_sum(grid): # O(m * n) time, O(n) space
row = []
for r, line in enumerate(grid):
for c, x in enumerate(line):
if r == 0:
row.append(x + (row[c - 1] if c else 0))
elif c == 0:
row[0] += x # only from above
else:
row[c] = x + min(row[c], row[c - 1]) # up, left
return row[-1]
print(min_path_sum([[1, 2, 3], [4, 5, 6]])) # 12
print(min_path_sum([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) # 7Edit distance with the actual edits
"kitten" to "sitting" needs 3 edits. To list them, fill the full table, then walk back from the bottom-right corner. At each cell, if the letters match, step diagonally for free. Otherwise, find which neighbour plus one gives this cell's value: diagonal means replace, up means delete from the first word, left means insert. The walk produces edits backwards, so reverse them at the end.
def edit_ops(a, b):
m, n = len(a), len(b)
dp = [[i + j if i * j == 0 else 0 for j in range(n + 1)] for i in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
dp[i][j] = dp[i-1][j-1] if a[i-1] == b[j-1] else 1 + min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1])
ops, i, j = [], m, n
while i or j:
if i and j and a[i-1] == b[j-1]: i, j = i - 1, j - 1
elif i and j and dp[i][j] == dp[i-1][j-1] + 1: ops.append(f"replace {a[i-1]}->{b[j-1]}"); i, j = i - 1, j - 1
elif i and dp[i][j] == dp[i-1][j] + 1: ops.append(f"delete {a[i-1]}"); i -= 1
else: ops.append(f"insert {b[j-1]}"); j -= 1
return dp[m][n], ops[::-1]
print(edit_ops("kitten", "sitting"))
# (3, ['replace k->s', 'replace e->i', 'insert g'])Quick reference
- Grid DP needs restricted moves (like right and down); four-way moves need BFS or Dijkstra
- Sequence DP tables are (m + 1) x (n + 1); row 0 and column 0 mean empty prefixes
- Build rows with [[0] * n for _ in range(m)], never [[0] * n] * m
- Unique paths without obstacles = math.comb(m + n - 2, m - 1)
- One-row unique paths: row[c] += row[c - 1]
- One-row edit distance: save the old row[j] as the next diagonal
- Edit distance: O(m x n) time; O(min(m, n)) space if you do not need the edits
- Reconstruct by walking back from dp[m][n] and matching each value to its source
Common mistakes
- Off-by-one errors between string indexes and table indexes.
- Creating rows with [[0] * n] * m, which aliases one row.
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
Count right-or-down paths in a grid where 1 marks an obstacle. Example: [[0,0,0],[0,1,0],[0,0,0]] gives 2.
- Exercise 2medium
Given a grid of "0" and "1" strings, return the area of the largest square made only of "1". Example below gives 4.
- Exercise 3hard
Write edit distance in O(min(m, n)) extra space.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I know a problem needs 2D DP?
- If one index is not enough to describe what is left to solve, add another. Two strings, a grid, or one position plus a remaining budget are the usual signs.
- Why does my table have one extra row and column?
- Row 0 and column 0 stand for empty prefixes. They hold simple base cases and remove the special cases at the edges.
- Is edit distance the same as Levenshtein distance?
- Yes, Levenshtein distance is edit distance with insert, delete and replace each costing 1. Variants add swaps of neighbouring letters (Damerau-Levenshtein) or allow different costs.