DP on two strings: i, j and what matches
1 What a diff tool keeps
A diff tool compares two versions of a file. It marks each line as kept, removed (−) or added (+). A good diff keeps as many lines as it can, in the same order in both versions, so it shows the fewest changes.
We use letters in place of lines, so the tables stay small. The old version is "bread" and the new one is "beard":
The kept letters appear in both words in the same order. Letters left after deleting some, in their order, form a subsequence. The kept part is the longest common subsequence, or LCS. Here it is "bead", of length 4.
Trying every subsequence of one word is about 2ᵐ checks for m letters. At 1000 letters that is far past the time limit: TLE. A table of m · n cells finds the LCS instead. The same table, with a different rule in each cell, solves most problems that compare two strings.
2 The state: two prefixes
In code, the two words are text1 and text2, with lengths m and n. We ask one question for every pair of prefixes:
The answer is lcs[m][n]. The state has two numbers, so the table has two sides. Each row stands for a prefix of text1, and each column for a prefix of text2:
Row 0 and column 0 stand for the empty prefix. An empty string shares nothing, so they hold 0. This is the leading 0 of prefix sums again: one extra row and column, so the first letter needs no if.
The extra row shifts the indexes by one. lcs[i][j] covers the first i letters, so the last of them is text1[i - 1], not text1[i]. Most bugs in these problems start here.
3 The rule: what matches
Each cell looks only at the last letter of each prefix, text1[i - 1] and text2[j - 1]. There are two cases.
- They match. The letter joins the LCS, and the rest comes from the prefixes without it. That is the cell up and to the left,
lcs[i - 1][j - 1], the diagonal. - They differ. At least one of the two letters is not in the LCS, so we drop one. Dropping
text1's letter is the cell up,lcs[i - 1][j]. Droppingtext2's is the cell to the left,lcs[i][j - 1]. We take the larger.
Here is why each case is right:
- A mismatch can drop a letter. Both letters come last, so if both were in the common subsequence, they would pair with each other. They differ, so at least one is unused.
- A match is safe to take. Any LCS of the two prefixes can swap its last pair for this pair, which sits at the very end of both. The length stays the same.
As in the grid lesson, we fill the table row by row, left to right. Then up, left and the diagonal are always filled before the cell that reads them.
4 Filling the table
Here are a few cells of the fill, in the order the loop reaches them. Blue marks the cell being filled and its two letters. Orange marks the cells it reads:
In step 4, "bre" and "bea" end in different letters. Dropping the a leaves "bre" and "be", which share "be", so the left cell wins with 2. The full table, with the matching letters' cells in blue:
A value spreads right and down until the next match raises it. The bottom-right cell is 4, the LCS of the whole words.
Every tab returns 4 for "bread" and "beard", 0 for "abc" and "xyz", and 1000 for two strings of 1000 as.
C++
A table of vectors. The table is m + 1 rows, and each row is its own vector<int> of n + 1 zeros.
charAt reads a letter. A Java String has no []. A new int[m + 1][n + 1] starts full of 0s, so row 0 and column 0 need no loop.
Build the rows in a loop. [[0] * (n + 1)] * (m + 1) looks the same, but every row is one shared list. Writing a cell in one row writes it in all of them.
Array.from makes separate rows. new Array(m + 1).fill(new Array(n + 1)) would put one shared row in every slot, and a write to one row would show in all.
Make each row. make([][]int, m+1) gives m + 1 empty rows, so each needs its own make([]int, n+1). Indexing a Go string gives a byte, which is fine for letters a to z.
Compare bytes. A Rust String cannot be indexed by position, so as_bytes() gives a slice we can. For letters a to z, one byte is one letter.
int[,] is one block. A rectangular array is indexed lcs[i, j] and starts full of 0s.
5 Reading the subsequence back
The table holds the length, but the letters are in it too. We start at the bottom-right cell and walk back to row 0 or column 0, undoing each choice:
- The letters match. That letter is in the LCS. Take it and step diagonally.
- They differ. Step to the larger of up and left. It holds the same value as this cell, so the value came from there.
Blue marks the path so far, and orange marks the cells where a letter is taken:
| Cell | Letters | Move | Taken |
|---|---|---|---|
| (5, 5) | d, d | diagonal | d |
| (4, 4) | a, r | left, which holds 3 | |
| (4, 3) | a, a | diagonal | a |
| (3, 2) | e, e | diagonal | e |
| (2, 1) | r, b | up, which holds 1 | |
| (1, 1) | b, b | diagonal | b |
The walk takes d, a, e, b, last letter first. Reversed, that is "bead". The walk is at most m + n steps, because each one leaves a row, a column or both.
i = m, j = n
while i > 0 and j > 0:
if text1[i - 1] == text2[j - 1]:
add text1[i - 1] to the answer
i = i - 1, j = j - 1
else if lcs[i - 1][j] >= lcs[i][j - 1]:
i = i - 1
else:
j = j - 1
reverse the answer
When up and left hold the same value, either step gives a correct LCS. Different choices can give different subsequences of the same length.
6 Edit distance: same table, new rule
The diff tool can also count changes. The edit distance is the fewest single-letter edits that turn text1 into text2. An edit inserts a letter, deletes one, or replaces one.
The state has the same shape. edits[i][j] is the fewest edits that turn the first i letters of text1 into the first j letters of text2. Each move maps to one neighbour:
| Move | What it does | Reads |
|---|---|---|
Delete text1[i - 1] | text1's prefix loses its last letter | up, + 1 |
Insert text2[j - 1] | the new letter is written at the end | left, + 1 |
Replace text1[i - 1] | the last letters now match | diagonal, + 1 |
| Match | the last letters are already equal | diagonal, free |
On a mismatch, we take the cheapest move. The base cases change too. Turning i letters into nothing takes i deletions, so column 0 holds i. Building j letters from nothing takes j inserts, so row 0 holds j.
The answer is 2: delete the r after b, and insert an r before d. That is the diff from the first section. Three replacements, r to e, e to a and a to r, would also work, but they cost 3.
The loop is the LCS loop with two changes: the base cases, and the cell rule.
diagonal = edits[i - 1][j - 1]
up = edits[i - 1][j]
left = edits[i][j - 1]
if text1[i - 1] == text2[j - 1]:
edits[i][j] = diagonal
else:
edits[i][j] = 1 + min(diagonal, up, left)
7 Cost, and saving space
The table has (m + 1) · (n + 1) cells, and each does a fixed amount of work. So time and space are both O(m · n). At m = n = 1000, that is about 10⁶ cells, well inside the time limit.
When only the number is needed, a row reads only itself and the row above, as in the lesson on keeping the last few states. Two rows, prev and curr, are enough, and space drops to O(n).
One row works too. We write the new row over the old one, left to right. Halfway through row 3, the slots left of j are new, and the rest still hold row 2:
Slot j still holds up, and slot j − 1 holds left. The diagonal was the old slot j − 1, overwritten one step ago. So we save each slot's old value before writing it, and it becomes the next diagonal:
for i from 1 to m:
diagonal = 0 // column 0 of the row above
for j from 1 to n:
up = row[j]
if text1[i - 1] == text2[j - 1]:
row[j] = diagonal + 1
else:
row[j] = max(up, row[j - 1])
diagonal = up
A problem that asks for the letters keeps the whole table for the walk back.
8 Mistakes and edge cases
- Mixing table indexes and string indexes. Cell (i, j) compares
text1[i - 1]withtext2[j - 1].text1[i]is the wrong letter, and on the last row it is past the end of the string. - Adding 1 to the wrong cell on a match. Up or left may have used the same letter already, so a match builds on the diagonal. For
"aa"and"a", adding 1 to up gives 2, but the answer is 1. - The wrong base row for edit distance. Row 0 and column 0 count up from 0, not all 0s. With 0s,
"ab"to"b"gives 0 edits instead of 1. - Losing the diagonal in one row. On a match,
row[j - 1] + 1reads left, not the diagonal. For"a"and"aa"it gives 2 instead of 1. Resettingdiagonalonly once, before all rows, also gives 2 for"aaa"and"ab". - Walking back the wrong way on a mismatch. A diagonal step on a mismatch drops a letter of each string, and one may belong to the LCS. On our words, it reads back
"bd"instead of"bead".
9 When to use it, and other rules
The sign is two strings, or two arrays, compared one position at a time. The problem asks how alike they are, how to turn one into the other, or how many ways one hides in the other. The state is a prefix of each.
Only the rule changes: what a match does, what a mismatch does, and what row 0 and column 0 hold.
| Problem | Match | Mismatch | Row 0, column 0 |
|---|---|---|---|
| Longest common subsequence | diagonal + 1 | larger of up and left | 0 |
| Edit distance | diagonal | 1 + smallest of three | j, i |
| Longest common substring | diagonal + 1 | 0 | 0 |
| Shortest common supersequence | diagonal + 1 | 1 + smaller of up and left | j, i |
Ways text2 hides in text1 | diagonal + up | up | 1 in column 0, else 0 |
A common substring must be one unbroken run, so a mismatch resets the cell to 0, and the answer is the largest cell. When counting ways, a matching letter of text1 can be used or skipped, so both counts add up.
A string compared with itself reversed is also two strings. The next lesson moves to a different shape of state: a range of one array, split at every point.
Practice it
- Longest Common SubsequenceMedium
- Maximum Length of Repeated SubarrayMedium
- Edit DistanceMedium
- Longest Palindromic SubsequenceMedium
- Distinct SubsequencesHard
- Interleaving StringMedium
- Wildcard MatchingHard
- Regular Expression MatchingHard
- Print a longest common subsequenceMedium
- Delete Operation for Two StringsMedium
- Minimum Insertion Steps to Make a String PalindromeHard
- Shortest Common Supersequence Hard
- Count palindromic subsequencesHard
- Minimum ASCII Delete Sum for Two StringsMedium
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.