Lesson 3 of 5
Grids and two strings
Some subproblems need two numbers to name them, a row and a column of a grid, or how far along each of two strings you are. The table gets a second index, each cell reads a few neighbors that are already filled, and filling row by row answers unique paths, longest common subsequence and edit distance.
Say a two-index state in words, such as "
best[i][j]is the answer for the first i letters of one string and the first j of the other"Name the neighbor cells each cell reads, and pick a fill order that has them ready
Set the base cases in row 0 and column 0, with an extra row and column for the empty prefix
Trace and write unique paths, longest common subsequence and edit distance in O(m × n) time
Keep only two rows of the table when a follow-up asks for less memory
Two systems hold the same customer. The CRM says Jon Smyth; billing says John Smith. How far apart are the two spellings? Count the fewest one-letter edits (insert, delete or replace one letter) that turn one into the other: insert an h, then replace the y with an i. Two edits. A dedupe job asks that question for every pair of names it compares, and the answer comes from a table whose rows follow one string and whose columns follow the other.
Reminder: dynamic programming (DP) answers each smaller version of a problem (a subproblem) once, stores the answers in a table, and builds bigger answers from smaller ones. The DP recipe has five parts: what a cell means (the state), how it is computed from smaller cells (the transition), the base cases (cells filled without reading any other cell), where the answer sits, and the fill order. In the last lesson, dp[i] named each subproblem with one number. Here a subproblem needs two: a row and a column, or a position in each of two strings.
Two numbers name a cell
How many routes cross a grid? A cart starts in the top-left cell of a warehouse floor drawn as a grid and must reach the bottom-right cell, moving one cell right or one cell down at a time. On a grid with 3 rows and 4 columns, every route makes 2 moves down and 3 moves right in some order, such as RRRDD or DRDRR (R for right, D for down). How many routes are there? Try listing them before you read on.
Name a cell (r, c): row r and column c, both counted from 0. The brute force follows the choices. From a cell, the routes to the end are the routes that go right first plus the routes that go down first, and a cell in the last row or the last column has one straight route left. Here it is on a 10 by 10 grid. visits is a Counter (the counting dict from module 3) that records how many times each cell's call runs.
It counts 48,620 routes with 97,239 calls, on a grid of only 100 cells. It reaches every route separately: the call for cell (5, 5) runs 252 times, once for every route from the start that passes through it, and each time it recounts the same routes from there to the end.
Each cell needs counting only once. A memo keyed by (r, c) would do it. A table does it with plain loops, and the loops can start at the top-left corner if we turn the question around and count the routes that arrive. The last move into (r, c) came from the cell above or from the cell to its left, never both, so the routes into (r, c) are the routes into those two cells added together. The recipe:
- State:
ways[r][c]is the number of routes from the start to cell(r, c). - Transition:
ways[r][c] = ways[r - 1][c] + ways[r][c - 1]. - Base cases: every cell in row 0 and column 0 is 1. Along the top edge the only route keeps moving right, down the left edge it keeps moving down, and the start has one route with no moves.
- Answer: the bottom-right cell,
ways[rows - 1][cols - 1]. - Order: row by row from the top, left to right, so the cell above and the cell to the left are always filled first.
The widget fills the table for 3 rows and 4 columns. It calls the table dp, so its dp[r][c] is our ways[r][c]. Shaded cells are base cases, the blue cell is being filled, and amber arrows point from the cells it reads. Before you press Next cell, guess the number in the bottom-right corner: it is the count of routes you tried to list.
Here is the same fill in Python, drawn as a grid with row and column numbers. Line 2 fills every row with 1s, which sets all the base cases at once; the loops then overwrite every cell outside row 0 and column 0. Line 2 is a list comprehension (a loop that builds a list in one line), and _ is the usual name for a loop variable nobody reads. It makes a new row on each pass. [[1] * cols] * rows would put one shared row in every position, the shared-row trap from module 1. Before you step through, say how many times line 5 runs.
def unique_paths(rows, cols):ways = [[1] * cols for _ in range(rows)]for r in range(1, rows):for c in range(1, cols):ways[r][c] = ways[r - 1][c] + ways[r][c - 1]return ways[rows - 1][cols - 1]
(nothing printed yet)The promise is the proof. The two cells a cell reads were filled first, so by the promise they are already right, and every route into the cell comes through exactly one of them. So the new cell is right too, and so is every cell after it, the bottom-right one included.
Now predict a table yourself: the same code on the grid turned on its side.
This builds the routes table for a grid with 4 rows and 3 columns, then prints it one row per line. Type exactly what it prints.
rows, cols = 4, 3
ways = [[1] * cols for _ in range(rows)]
for r in range(1, rows):
for c in range(1, cols):
ways[r][c] = ways[r - 1][c] + ways[r][c - 1]
for row in ways:
print(row)
Row by row is the usual order, not the only one. Any order works if each cell is filled after the cells it reads.
The routes table for the 3 by 4 grid fills row by row, left to right, starting from a grid full of 1s. Which other order also gives every cell the right count?
Choose one answer, then check.
Now write it yourself. Say the state in words before you type.
One row or one column is the edge case to say out loud: no cell is updated, and the answer stays 1. Return ways[rows - 1][cols - 1]; ways[rows][cols] is outside the grid.
Change what a cell holds, and the same walk answers a new question: the cheapest route across a grid of costs.
Every cell of the warehouse grid now has a cost: costs[r][c]. A route still moves one cell right or one cell down at a time, and its cost is the sum of every cell it visits, both ends included.
Write cheapest_route(costs), which returns the smallest cost of any route from the top-left cell to the bottom-right cell. The grid has at least one cell, and every cost is 0 or more. For [[3, 1, 7], [2, 9, 1], [1, 1, 4]] the answer is 11: down, down, right, right, for 3 + 2 + 1 + 1 + 4.
raise NotImplementedError, then press Run tests. Each check says what it expects.Two strings, one prefix each
What does a cell mean when the input is two strings? A subsequence of a string is what is left after deleting any letters you like (possibly none) without changing the order of the rest: "ct" is a subsequence of "cat". The longest common subsequence (LCS) of two strings is the longest string that is a subsequence of both. For "cat" and "act" it has length 2, "ct" or "at". Not 3, because order matters: the c comes before the a in "cat" and after it in "act".
A prefix is the start of a string: first[:i] is the first i letters of first. A cell here names a pair of prefixes: best[i][j] is the LCS length of first[:i] and second[:j]. Prefixes work because dropping the last letter of a prefix leaves a shorter prefix, which is another cell of the same table.
Compare the last letters of the two prefixes, first[i - 1] and second[j - 1]:
- Equal: that letter can end a common subsequence of both, so the answer is 1 plus the answer without both letters:
best[i - 1][j - 1] + 1, the cell above-left. - Different: a common subsequence that used both would have to end with each of them, and they are different letters. So at least one is unused. Drop the last letter of
first(the cell above,best[i - 1][j]) or ofsecond(the cell to the left,best[i][j - 1]), and keep the larger.
Why is taking a match safe? Take any longest common subsequence of the two prefixes and swap its last letter for the matching pair at the very ends. Its other letters sit before its old last letter in both prefixes, so they also sit before the two ends: it is still a common subsequence, with the same length. So some longest answer ends with the match, and the rest of it is a common subsequence of the two shorter prefixes: the cell above-left.
Written as a recursion on the two prefix lengths, the rule is short:
def longest_common_subsequence(first, second):
def lcs(i, j): # the LCS length of first[:i] and second[:j]
if i == 0 or j == 0:
return 0 # an empty prefix shares nothing
if first[i - 1] == second[j - 1]:
return lcs(i - 1, j - 1) + 1
return max(lcs(i - 1, j), lcs(i, j - 1))
return lcs(len(first), len(second))
It is correct, and slow. While the last letters differ, every call makes two more. On two 10-letter strings with no letter in common it makes 369,511 calls, yet only 11 × 11 = 121 pairs (i, j) exist. A table with one cell per pair answers each pair once. (@cache on lcs would too: the memo from the lesson From recursion to memoization.)
Row 0 and column 0 stand for an empty prefix, the i == 0 or j == 0 case above: 0. So the table has one more row and one more column than the strings have letters, 4 by 4 for two 3-letter words.
The widget fills the table for "cat" down the side and "act" across the top. It calls the strings a and b, and its headers show each prefix, with "" for the empty one. Watch the arrows: one from above-left on a match, two (above and left) otherwise. Before you start, find the three pairs of equal letters.
Here is the code, with the table drawn as a grid: row i is first[:i] and column j is second[:j]. Before you step through, guess how many times line 7, the match line, runs.
def longest_common_subsequence(first, second):rows, cols = len(first), len(second)best = [[0] * (cols + 1) for _ in range(rows + 1)]for i in range(1, rows + 1):for j in range(1, cols + 1):if first[i - 1] == second[j - 1]:best[i][j] = best[i - 1][j - 1] + 1else:best[i][j] = max(best[i - 1][j], best[i][j - 1])return best[rows][cols]
(nothing printed yet)Many rounds have no run button, so at the whiteboard you fill a table like this by hand. Try one on new words.
On paper, fill the LCS table for first = "bake" (down the side) and second = "beak" (across the top). Draw 5 rows and 5 columns: row 0 and column 0 are for the empty prefix. Use the two rules: a match is 1 plus the cell above-left; otherwise take the larger of the cell above and the cell to the left. Reveal one row at a time to check, then type the bottom-right value.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now put the code together. Three of the lines are mistakes people make.
Put the lines in order to build longest_common_subsequence(first, second). Indentation is already part of each line. Three lines do not belong: each is a mistake people make with two-string tables.
Add lines from the list below, in order.
for i in range(1, rows + 1):else:for j in range(1, cols + 1):def longest_common_subsequence(first, second):rows, cols = len(first), len(second)return best[rows][cols]if first[i - 1] == second[j - 1]:if first[i] == second[j]:return best[rows - 1][cols - 1]best = [[0] * (cols + 1) for _ in range(rows + 1)]best[i][j] = best[i - 1][j - 1] + 1best = [[0] * (cols + 1)] * (rows + 1)best[i][j] = max(best[i - 1][j], best[i][j - 1])
Now write it yourself. The tests include repeated letters and inputs where matching the first equal letters you see gives the wrong answer.
Say the two edge cases out loud: identical strings match on every diagonal step, so the answer is the full length, and strings with no shared letter never add 1, so the answer is 0.
Recap: a two-string table has a row for each prefix of the first string and a column for each prefix of the second, the empty prefix included. Each cell compares two last letters: a match reads above-left, a mismatch reads above and left.
Three edits, three neighbors
How many edits turn one string into another? Back to Jon Smyth and John Smith. An edit inserts one letter, deletes one letter, or replaces one letter with a different one. The edit distance is the fewest edits that turn the first string, the source, into the second, the target.
The table has the LCS shape: edits[i][j] is the fewest edits that turn source[:i] into target[:j]. The base cases are not 0. Turning i letters into the empty string takes i deletes, so edits[i][0] = i; building j letters from nothing takes j inserts, so edits[0][j] = j.
Look at the last letters, source[i - 1] and target[j - 1]. If they match, keep them for free: edits[i][j] = edits[i - 1][j - 1]. If not, one edit deals with them, and each kind of edit points at one neighbor:
- Delete
source[i - 1], then turnsource[:i - 1]intotarget[:j]: the cell above,edits[i - 1][j]. - Insert
target[j - 1]at the end, after turningsource[:i]intotarget[:j - 1]: the cell to the left,edits[i][j - 1]. - Replace
source[i - 1]withtarget[j - 1], then turnsource[:i - 1]intotarget[:j - 1]: the cell above-left,edits[i - 1][j - 1].
So a mismatch costs 1 + min(above, left, above-left). The plain recursion tries all three edits at every mismatch, three calls each time, and it meets the same pairs (i, j) again and again, as the LCS recursion did. The table answers each pair once.
Why is keeping a match for free safe? One extra letter in either string changes the answer by at most 1, because one more delete or insert takes care of it. So above-left is at most 1 more than above, and at most 1 more than left, and taking it for free is never worse than paying 1.
The widget fills the table for "ear" into "are", again calling the strings a and b. A mismatch draws three arrows, and the text names the cheapest edit. The two words use the same three letters; before you start, guess how many edits they need.
Here is the code. The mismatch branch names its three choices, so the trace shows each value before the minimum is taken. Before you step through, guess how many times line 16, the mismatch line, runs.
def edit_distance(source, target):rows, cols = len(source), len(target)edits = [[0] * (cols + 1) for _ in range(rows + 1)]for i in range(rows + 1):edits[i][0] = ifor j in range(cols + 1):edits[0][j] = jfor i in range(1, rows + 1):for j in range(1, cols + 1):if source[i - 1] == target[j - 1]:edits[i][j] = edits[i - 1][j - 1]else:delete = edits[i - 1][j]insert = edits[i][j - 1]replace = edits[i - 1][j - 1]edits[i][j] = 1 + min(delete, insert, replace)return edits[rows][cols]
(nothing printed yet)Each neighbor stands for one kind of edit. Check that you can name them.
In the edit distance table, edits[i][j] can be the cell above, edits[i - 1][j], plus 1. Which edit does that step pay for?
Choose one answer, then check.
Take away one kind of edit and the answer can never go down. Without replace, a changed letter costs a delete and an insert.
Suppose replace is not allowed: only inserts and deletes, each costing 1. How many edits turn "cat" into "cut"? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now write it yourself, base-case loops first.
An empty source or target is the edge case: no inner cell is filled, and the base case is the answer. One follow-up connects back to LCS: if a replace cost 2, it would never beat a delete plus an insert, so the answer becomes m + n − 2 × LCS for strings of lengths m and n, the count from the exercise above.
One shape, three rules
Side by side, the three tables differ only in what a cell means and how it combines its neighbors:
| Problem | A cell means | It reads | Base cases |
|---|---|---|---|
| Unique paths | routes into (r, c) | above plus left | row 0 and column 0 are 1 |
| Longest common subsequence | LCS of first[:i] and second[:j] | match: above-left plus 1; else the larger of above and left | row 0 and column 0 are 0 |
| Edit distance | fewest edits from source[:i] to target[:j] | match: above-left; else 1 plus the smallest of above, left and above-left | edits[i][0] = i, edits[0][j] = j |
Every cell reads only cells above it or to its left, so row by row, left to right, works for all three. For a table of m rows and n columns, that is O(m × n) time.
Each row reads only itself and the row above, so two rows are enough: O(n) space instead of O(m × n), your answer when a follow-up asks for less memory. Here is LCS with two rows. prev is row i - 1 and cur is row i, so every best[i - 1][...] becomes prev[...] and every best[i][...] becomes cur[...].
def longest_common_subsequence(first, second):
cols = len(second)
prev = [0] * (cols + 1) # row 0: the empty prefix of first
for i in range(1, len(first) + 1):
cur = [0] * (cols + 1) # row i; cur[0] = 0 is its base case
for j in range(1, cols + 1):
if first[i - 1] == second[j - 1]:
cur[j] = prev[j - 1] + 1
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur # row i becomes the row above
return prev[cols]
For edit distance, the base cases come along: start prev as list(range(cols + 1)), which is row 0, and set cur[0] = i at the start of each row, because column 0 is not 0 there. The price is the path: with two rows left, you cannot walk back through the table to recover the letters or the edits.
Two more two-index tables wait in this module's practice bank. Interleaving string (LeetCode 97) has this lesson's shape: a cell for each pair of prefixes, reading above and left. Longest palindromic substring (LeetCode 5) indexes one string twice, by where a stretch starts and where it ends, and each cell reads the stretch one letter shorter at both ends.
Last, practice saying it. The words you write here are the words you will say in the room.
An interviewer asks for the fewest inserts, deletes and replaces that turn one word into another. Explain your plan before you type: the brute force and why it is slow, the state, the transition, the base cases, and the cost.
Saved in this browser as you type.