Skip to content

Lesson 26 of 40Advanced patterns

2D Dynamic Programming

Solve grid paths, longest common subsequence and edit distance by filling a 2D table cell by cell.

20 min read0/4 questions

When git diff shows which lines changed, when a search box says "did you mean receive?", when a DNA tool lines up two sequences: each of those is a two-dimensional DP. The state needs two numbers, usually "how far into the first input" and "how far into the second", so the table becomes a grid.

The recipe from the last lesson does not change: state, recurrence, base cases, order, answer. What is new is learning to read the recurrence off the grid: each cell looks at its neighbours above, to the left, and diagonally up-left.

Grid paths: the warm-up

A robot starts at the top-left of an m × n grid and can only move right or down. How many different paths reach the bottom-right?

  • State: dp[r][c] = number of paths from the start to cell (r, c).
  • Recurrence: the last move into (r, c) came from above or from the left, so dp[r][c] = dp[r-1][c] + dp[r][c-1].
  • Base cases: the whole top row and left column are 1 (only one way to go straight).
  • Order: row by row, left to right, so above and left are ready.
  • Answer: dp[m-1][n-1].
Unique paths in a 3 × 4 grid
1111
1
1

Base cases: one way to reach any cell in the top row (all rights) or left column (all downs).

1/5
Python
def unique_paths(m, n): dp = [[1] * n for _ in range(m)] for r in range(1, m): for c in range(1, n): dp[r][c] = dp[r - 1][c] + dp[r][c - 1] return dp[m - 1][n - 1] print(unique_paths(3, 4), unique_paths(3, 7), unique_paths(1, 5))
Output
Press Run (⌘ Enter) to see what happens.
Quick check
Now some cells are blocked by rocks. What changes in the recurrence?
Need a nudge? A hint rules out a wrong answer.

Longest common subsequence

A subsequence keeps some characters in their original order, possibly skipping others: "ace" is a subsequence of "abcde". The longest common subsequence (LCS) of two strings is the longest string that is a subsequence of both. diff tools use it: lines in the LCS are unchanged, everything else was added or removed.

  • State: dp[i][j] = LCS length of the first i characters of a and the first j of b.
  • Recurrence: look at the last characters, a[i-1] and b[j-1].
    • If they match, they extend the LCS of both prefixes without them: dp[i][j] = dp[i-1][j-1] + 1 (diagonal + 1).
    • If not, one of them is not in the LCS. Drop either and take the better: dp[i][j] = max(dp[i-1][j], dp[i][j-1]) (above or left).
  • Base cases: row 0 and column 0 are 0 (an empty string has nothing in common with anything).
  • Answer: dp[len(a)][len(b)].
LCS of abcde (rows) and ace (columns)
∅ace
∅0000
a0
b0
c0
d0
e0

The extra row and column stand for the empty prefix. They are all 0.

1/5
Python
def lcs(a, b): dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)] for i in range(1, len(a) + 1): for j in range(1, len(b) + 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[len(a)][len(b)] print(lcs("abcde", "ace"), lcs("abc", "def"), lcs("kitten", "sitting"))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

print(lcs("abc", "cab"))
Need a nudge? Hints walk you through it.

Edit distance

The edit distance (Levenshtein distance) between two words is the fewest single-character inserts, deletes or replacements that turn one into the other. Spell checkers suggest the dictionary words with the smallest edit distance from what you typed.

  • State: dp[i][j] = edits to turn the first i letters of a into the first j letters of b.
  • Base cases: dp[i][0] = i (delete everything), dp[0][j] = j (insert everything).
  • Recurrence: if a[i-1] == b[j-1], no edit is needed: dp[i][j] = dp[i-1][j-1]. Otherwise it is 1 plus the cheapest of three moves:
    • replace: diagonal, dp[i-1][j-1]
    • delete from a: above, dp[i-1][j]
    • insert into a: left, dp[i][j-1]
Edit distance: horse (rows) to ros (columns)
∅ros
∅0123
h1
o2
r3
s4
e5

Base cases. Turning hor into the empty string takes 3 deletes; turning empty into ro takes 2 inserts.

1/5
Python
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 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], # replace dp[i - 1][j], # delete dp[i][j - 1]) # insert return dp[m][n] print(edit_distance("horse", "ros"), edit_distance("kitten", "sitting"), edit_distance("", "abc"))
Output
Press Run (⌘ Enter) to see what happens.
Match the pairs0/4 matched

In the edit distance table, match each neighbour of cell (i, j) to the edit it represents.

Choose an item, then its match on the other side.

Saving space: two rows

Look at what each cell reads: the row above and the current row to its left. Nothing older. So you never need the whole table, only the previous row and the current one. That drops space 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]

Unique paths can go further and use a single row, updating row[c] += row[c - 1] in place, because the old value of row[c] is exactly "above". The tradeoff: once you throw rows away, you can no longer walk back through the table to recover the actual subsequence or list of edits, only its length.

Quick check
Your LCS uses the two-row trick. Your manager now wants the actual common lines shown in a diff view. What is the problem?
Need a nudge? A hint rules out a wrong answer.

Common mistakes:

  • Indexing the strings with a[i] instead of a[i-1]. With the extra empty row, table index i means "first i characters", whose last character is a[i-1].
  • Forgetting the base row and column (edit distance starts with 0, 1, 2, …, not zeros).
  • Building rows with [[0] * n] * m in Python. That makes m references to one list; use a comprehension.
  • Overwriting values you still need when compressing to one row.
ChallengeMedium

Unique Paths

A robot starts in the top-left cell of an m × n grid and wants to reach the bottom-right cell. It can only move right or down. Return how many different paths it can take.

m = 3, n = 2  →  3   (right-down-down, down-right-down, down-down-right)
m = 3, n = 7  →  28
m = 1, n = 1  →  1

Constraints

  • 1 <= m, n <= 100
  • The answer is at most 2 * 10^9.
def unique_paths(m: int, n: int) -> int: # Each cell is reached from the cell above or the cell to the left. pass
ChallengeMedium

Longest Common Subsequence

Return the length of the longest subsequence that appears in both strings a and b. A subsequence keeps the original order but may skip characters. Return 0 if they share nothing.

a = "abcde", b = "ace"  →  3   ("ace")
a = "abc",   b = "abc"  →  3
a = "abc",   b = "def"  →  0

Constraints

  • 0 <= a.length, b.length <= 1000
  • Both strings contain only lowercase letters.
def longest_common_subsequence(a: str, b: str) -> int: # Compare the strings prefix by prefix in a 2D table. pass
Key terms
2D DP
DP where the state needs two indices, typically prefixes of two inputs or a grid cell.
subsequence
Characters kept in their original order with any others skipped. ace is a subsequence of abcde.
LCS
Longest common subsequence: match means diagonal + 1, otherwise the max of above and left.
edit distance
Fewest inserts, deletes and replacements to turn one string into another. Diagonal, above, left map to replace, delete, insert.
rolling rows
Keep only the previous and current row when each cell reads nothing older. Cuts space to O(n).