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.
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, sodp[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].
Base cases: one way to reach any cell in the top row (all rights) or left column (all downs).
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.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 firsticharacters ofaand the firstjofb. - Recurrence: look at the last characters,
a[i-1]andb[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).
- If they match, they extend the LCS of both prefixes without them:
- Base cases: row 0 and column 0 are 0 (an empty string has nothing in common with anything).
- Answer:
dp[len(a)][len(b)].
The extra row and column stand for the empty prefix. They are all 0.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.What does this print?
print(lcs("abc", "cab"))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 firstiletters ofainto the firstjletters ofb. - 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]
- replace: diagonal,
Base cases. Turning hor into the empty string takes 3 deletes; turning empty into ro takes 2 inserts.
Press Run (⌘ Enter) to see what happens.In the edit distance table, match each neighbour of cell (i, j) to the edit it represents.
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.
Common mistakes:
- Indexing the strings with
a[i]instead ofa[i-1]. With the extra empty row, table indeximeans "first i characters", whose last character isa[i-1]. - Forgetting the base row and column (edit distance starts with
0, 1, 2, …, not zeros). - Building rows with
[[0] * n] * min Python. That makes m references to one list; use a comprehension. - Overwriting values you still need when compressing to one row.
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 → 1Constraints
1 <= m, n <= 100- The answer is at most
2 * 10^9.
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" → 0Constraints
0 <= a.length, b.length <= 1000- Both strings contain only lowercase letters.
- 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.
aceis a subsequence ofabcde. - 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).