DP on two strings: i, j and what matches

Video lessonComing soon

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":

b0r1e2a3d4
Old: r removed
b0e1a2r3d4
New: r added

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:

lcs[i][j] = the LCS of the first i letters of text1 and the first j letters of text2

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:

beard000000b0r0e0a0d0
Rows: prefixes of bread. Columns: prefixes of beard

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]. Dropping text2's is the cell to the left, lcs[i][j - 1]. We take the larger.
match: lcs[i][j] = diagonal + 1
mismatch: lcs[i][j] = max(up, left)

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:

Filling lcs for bread and beard
beard000000b0r0e0a0d0
Row 0 and column 0: empty, so 0

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:

beard000000b011111r011122e012222a012333d012334
Blue: the matches. A number goes up only at a match

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:

Walking back from lcs[5][5]
beard000000b011111r011122e012222a012333d012334
d = d: take d, step diagonally
CellLettersMoveTaken
(5, 5)d, ddiagonald
(4, 4)a, rleft, which holds 3
(4, 3)a, adiagonala
(3, 2)e, ediagonale
(2, 1)r, bup, which holds 1
(1, 1)b, bdiagonalb

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:

MoveWhat it doesReads
Delete text1[i - 1]text1's prefix loses its last letterup, + 1
Insert text2[j - 1]the new letter is written at the endleft, + 1
Replace text1[i - 1]the last letters now matchdiagonal, + 1
Matchthe last letters are already equaldiagonal, 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.

Filling edits for bread and beard
beard012345b1r2e3a4d5
Row 0: inserts. Column 0: deletes

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:

001122132425j
Slots 0 to 2 are row 3, slots 3 to 5 row 2
1diagonal
Old slot 2, saved before it changed

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] with text2[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] + 1 reads left, not the diagonal. For "a" and "aa" it gives 2 instead of 1. Resetting diagonal only 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.

ProblemMatchMismatchRow 0, column 0
Longest common subsequencediagonal + 1larger of up and left0
Edit distancediagonal1 + smallest of threej, i
Longest common substringdiagonal + 100
Shortest common supersequencediagonal + 11 + smaller of up and leftj, i
Ways text2 hides in text1diagonal + upup1 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.

Before writing the loop, say in words what cell (i, j) means for the first i and the first j letters. Then fill in the match, the mismatch, and row 0 and column 0.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.