Build a table over two prefixes for deletions, edit distance and interleaving, and over one string for palindromes.
You work on the search box of an online store. Someone types lemon, and the store sells melon. Your team lead asks: "How close are these two words, and which product is the closest to what was typed?"
Measure closeness as the fewest single-letter edits. An edit inserts a letter, deletes a letter, or replaces one letter by another. Turning lemon into melon by hand takes two replaces: l becomes m, and m becomes l. One edit is not enough, because the two words differ in two places.
Now compare many words. For each pair, the store needs the fewest edits, fast. A table over the letters of both words will give it.
The first attempt is correct. Compare the words from the first letter. When the letters are equal, move on at no cost. When they differ, try a delete, an insert and a replace, and keep the cheapest.
Now check the real size. For lemon and melon this makes 382 calls. For two words of 10 letters with no letter in common it makes 12,146,179 calls. The same pair of positions is reached again and again, by different orders of edits.
A copy editor has a draft and the final text. She reads both from the start. When the next words match, she moves on. When they differ, she has three tools: cross out a word, add a word, or write a new word over the old one.
She wants the fewest marks. The best marks for the first words never depend on how she got there. So she keeps a note of the best count for each pair of positions.
That note is a table over two strings. Each cell holds the best count for one pair of prefixes.
A copy editor compares a draft with the final text using three marks: cross out, add or write over. A table keeps the best count for each pair.
Predict what happens
Q You turn lemon into melon. The first letters, l and m, differ. How many different edits could you try on this pair?
Answer: B
Different letters give three choices: a delete, an insert and a replace. A table keeps the cheapest result for every pair of positions, so each pair is solved once.
Let dist[i][j] be the fewest edits that turn the first i letters of lemon into the first j letters of melon. The first 0 letters are nothing. Turning nothing into j letters takes j insertions, and turning i letters into nothing takes i deletions. These are the first row and the first column.
For any other cell, look at the last letters of the two prefixes. If they are equal, no edit is needed for them, and the answer is the diagonal cell. If they differ, one edit is needed on top of the cheapest of three smaller pairs.
| Neighbour | What it means |
|---|---|
Diagonal: dist[i - 1][j - 1] |
The last letters are matched, or one replaces the other |
Above: dist[i - 1][j] |
The last letter of the source is deleted |
Left: dist[i][j - 1] |
The last letter of the target is inserted |
Here is the whole table for lemon and melon.
| source \ target | (none) | m | e | l | o | n |
|---|---|---|---|---|---|---|
| (none) | 0 | 1 | 2 | 3 | 4 | 5 |
| l | 1 | 1 | 2 | 2 | 3 | 4 |
| e | 2 | 2 | 1 | 2 | 3 | 4 |
| m | 3 | 2 | 2 | 2 | 3 | 4 |
| o | 4 | 3 | 3 | 3 | 2 | 3 |
| n | 5 | 4 | 4 | 4 | 3 | 2 |
Check three cells. Cell (1, 1) compares l and m. They differ, so it is 1 plus the smallest of the diagonal 0, above 1 and left 1: 1.
Cell (2, 2) compares e and e. They are equal, so it copies the diagonal 1: 1.
Cell (4, 3) compares o and l. They differ, so it is 1 plus the smallest of the diagonal 2, above 2 and left 3: 3. The last cell holds 2.
A cell of the edit table reads the diagonal, the cell above and the cell to the left, and adds one to the smallest, unless the letters match.
A cell reads the cells above it, to its left and on its diagonal. So fill row by row, from the top, and left to right in each row. Then all three are ready when the cell needs them. This is the same order as the longest common subsequence and the routes on a grid.
The table does not change. Only the rule on a mismatch does. Here are the three results for lemon and melon.
| Question | On a mismatch | Result |
|---|---|---|
| Longest common subsequence | The larger of above and left | 3 letters |
| Fewest deletions, from both words | 1 plus the smaller of above and left | 4 |
| Edit distance | 1 plus the smallest of the three | 2 |
The deletions equal the two lengths minus twice the common letters: 5 + 5 - 2 × 3 = 4. Allowing a replace lowers 4 to 2.
Exercise · Break it: Find the input where comparing position by position fails. This function counts the edits by comparing the words position by position, plus the difference in length. Find two words where it gives more than the fewest edits.
def position_edits(source, target):
edits = abs(len(source) - len(target))
for a, b in zip(source, target):
if a != b:
edits += 1
return editsPredict what happens
Q In the edit table for lemon and melon, cell (4, 3) compares o and l. Which three cells does it read?
Answer: B
Each cell reads the cell above (a delete), the cell to the left (an insert) and the diagonal (a replace). All three are filled before it, because the table is filled row by row, left to right.
The visualizer fills a table over two words for the longest common subsequence and joins each cell to the cells it reads. The edit table has the same shape, with a minimum of three neighbours. Try these in order.
Step by step: A table for lemon and melon. The animated player loads in your browser.
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Every cell holds the best answer for one pair of prefixes. The cells it reads are pairs with one letter fewer on a side, so they were filled first and are already right.
Why is the table right? The first row and column are right by definition. Each other cell chooses among answers for smaller pairs, using a rule that is true for its own pair. So every cell is right, one after another, up to the last.
This code is the edit distance. It keeps only the previous row, because a row reads only the row above and the cell to its left.
def edit_distance(source, target):
m = len(target)
# [1] prev[j] is the fewest edits that turn the empty start of the source into the first j letters of the target: j insertions.
prev = list(range(m + 1))
# [2] Read the letters of the source one at a time, so prev holds the row for the letters before this one.
for i in range(1, len(source) + 1):
# [3] cur[0] is the fewest edits that turn the first i letters of the source into nothing: i deletions.
cur = [i] + [0] * m
for j in range(1, m + 1):
# [4] If the two letters are equal, no edit is needed for them: copy the diagonal cell.
if source[i - 1] == target[j - 1]:
cur[j] = prev[j - 1]
else:
# [5] Otherwise one edit is needed: a replace (the diagonal cell), a delete (the cell above) or an insert (the cell to the left). Take the cheapest and add 1.
cur[j] = 1 + min(prev[j - 1], prev[j], cur[j - 1])
# [6] The row just built becomes the previous row for the next letter.
prev = cur
# [7] The last cell is the fewest edits for the whole source and the whole target.
return prev[m]class Solution {
public int editDistance(String source, String target) {
int m = target.length();
// [1] prev[j] is the fewest edits that turn the empty start of the source into the first j letters of the target: j insertions.
int[] prev = new int[m + 1];
for (int j = 0; j <= m; j++) prev[j] = j;
// [2] Read the letters of the source one at a time, so prev holds the row for the letters before this one.
for (int i = 1; i <= source.length(); i++) {
// [3] cur[0] is the fewest edits that turn the first i letters of the source into nothing: i deletions.
int[] cur = new int[m + 1];
cur[0] = i;
for (int j = 1; j <= m; j++) {
// [4] If the two letters are equal, no edit is needed for them: copy the diagonal cell.
if (source.charAt(i - 1) == target.charAt(j - 1)) {
cur[j] = prev[j - 1];
} else {
// [5] Otherwise one edit is needed: a replace (the diagonal cell), a delete (the cell above) or an insert (the cell to the left). Take the cheapest and add 1.
cur[j] = 1 + Math.min(prev[j - 1], Math.min(prev[j], cur[j - 1]));
}
}
// [6] The row just built becomes the previous row for the next letter.
prev = cur;
}
// [7] The last cell is the fewest edits for the whole source and the whole target.
return prev[m];
}
}int editDistance(string source, string target) {
int m = target.size();
// [1] prev[j] is the fewest edits that turn the empty start of the source into the first j letters of the target: j insertions.
vector<int> prev(m + 1);
for (int j = 0; j <= m; j++) prev[j] = j;
// [2] Read the letters of the source one at a time, so prev holds the row for the letters before this one.
for (int i = 1; i <= (int) source.size(); i++) {
// [3] cur[0] is the fewest edits that turn the first i letters of the source into nothing: i deletions.
vector<int> cur(m + 1, 0);
cur[0] = i;
for (int j = 1; j <= m; j++) {
// [4] If the two letters are equal, no edit is needed for them: copy the diagonal cell.
if (source[i - 1] == target[j - 1]) {
cur[j] = prev[j - 1];
} else {
// [5] Otherwise one edit is needed: a replace (the diagonal cell), a delete (the cell above) or an insert (the cell to the left). Take the cheapest and add 1.
cur[j] = 1 + min(prev[j - 1], min(prev[j], cur[j - 1]));
}
}
// [6] The row just built becomes the previous row for the next letter.
prev = cur;
}
// [7] The last cell is the fewest edits for the whole source and the whole target.
return prev[m];
}function editDistance(source, target) {
const m = target.length;
// [1] prev[j] is the fewest edits that turn the empty start of the source into the first j letters of the target: j insertions.
let prev = Array.from({ length: m + 1 }, (_, j) => j);
// [2] Read the letters of the source one at a time, so prev holds the row for the letters before this one.
for (let i = 1; i <= source.length; i++) {
// [3] cur[0] is the fewest edits that turn the first i letters of the source into nothing: i deletions.
const cur = new Array(m + 1).fill(0);
cur[0] = i;
for (let j = 1; j <= m; j++) {
// [4] If the two letters are equal, no edit is needed for them: copy the diagonal cell.
if (source[i - 1] === target[j - 1]) {
cur[j] = prev[j - 1];
} else {
// [5] Otherwise one edit is needed: a replace (the diagonal cell), a delete (the cell above) or an insert (the cell to the left). Take the cheapest and add 1.
cur[j] = 1 + Math.min(prev[j - 1], prev[j], cur[j - 1]);
}
}
// [6] The row just built becomes the previous row for the next letter.
prev = cur;
}
// [7] The last cell is the fewest edits for the whole source and the whole target.
return prev[m];
}For lemon and melon it returns 2. For sunday and saturday it returns 3.
Exercise · Predict the output: The last row for ab and ba. The edit table is built for turning ab into ba, keeping only the previous row. What does the last row hold, from the first cell to the last?
source, target = "ab", "ba"
m = len(target)
prev = list(range(m + 1))
for i in range(1, len(source) + 1):
cur = [i] + [0] * m
for j in range(1, m + 1):
if source[i - 1] == target[j - 1]:
cur[j] = prev[j - 1]
else:
cur[j] = 1 + min(prev[j - 1], prev[j], cur[j - 1])
prev = cur
print(prev[0], prev[1], prev[2])The same shape answers a yes-or-no question. This code checks whether a third string is made by mixing two strings, keeping the order in each. A cell reads the cell above or the cell to the left, and each needs a matching letter.
def is_interleaving(first, second, merged):
n, m = len(first), len(second)
# [1] The merged string must hold exactly the letters of both strings, so the lengths must add up.
if n + m != len(merged):
return False
# [2] fits[j] says whether the first i letters of one string and the first j letters of the other can make the first i + j letters of the merged string. Before any letter of the first string is read, only the second string is used, and each step needs its letter to match.
fits = [False] * (m + 1)
fits[0] = True
for j in range(1, m + 1):
fits[j] = fits[j - 1] and second[j - 1] == merged[j - 1]
# [3] Read the letters of the first string one at a time, so fits holds the row for the previous count and becomes the row for this one.
for i in range(1, n + 1):
# [4] With no letters of the second string, the merged string must start with the letters of the first string in order.
fits[0] = fits[0] and first[i - 1] == merged[i - 1]
# [5] Letter i + j of the merged string came from the first string, which fits[j] still holds from the previous row, or from the second string, which fits[j - 1] holds in this row. Each needs its letter to match.
for j in range(1, m + 1):
fits[j] = (fits[j] and first[i - 1] == merged[i + j - 1]) or (fits[j - 1] and second[j - 1] == merged[i + j - 1])
# [6] The corner says whether both strings, used completely, make the whole merged string.
return fits[m]class Solution {
public boolean isInterleaving(String first, String second, String merged) {
int n = first.length();
int m = second.length();
// [1] The merged string must hold exactly the letters of both strings, so the lengths must add up.
if (n + m != merged.length()) return false;
// [2] fits[j] says whether the first i letters of one string and the first j letters of the other can make the first i + j letters of the merged string. Before any letter of the first string is read, only the second string is used, and each step needs its letter to match.
boolean[] fits = new boolean[m + 1];
fits[0] = true;
for (int j = 1; j <= m; j++) fits[j] = fits[j - 1] && second.charAt(j - 1) == merged.charAt(j - 1);
// [3] Read the letters of the first string one at a time, so fits holds the row for the previous count and becomes the row for this one.
for (int i = 1; i <= n; i++) {
// [4] With no letters of the second string, the merged string must start with the letters of the first string in order.
fits[0] = fits[0] && first.charAt(i - 1) == merged.charAt(i - 1);
// [5] Letter i + j of the merged string came from the first string, which fits[j] still holds from the previous row, or from the second string, which fits[j - 1] holds in this row. Each needs its letter to match.
for (int j = 1; j <= m; j++) {
fits[j] = (fits[j] && first.charAt(i - 1) == merged.charAt(i + j - 1))
|| (fits[j - 1] && second.charAt(j - 1) == merged.charAt(i + j - 1));
}
}
// [6] The corner says whether both strings, used completely, make the whole merged string.
return fits[m];
}
}bool isInterleaving(string first, string second, string merged) {
int n = first.size();
int m = second.size();
// [1] The merged string must hold exactly the letters of both strings, so the lengths must add up.
if (n + m != (int) merged.size()) return false;
// [2] fits[j] says whether the first i letters of one string and the first j letters of the other can make the first i + j letters of the merged string. Before any letter of the first string is read, only the second string is used, and each step needs its letter to match.
vector<char> fits(m + 1, 0);
fits[0] = 1;
for (int j = 1; j <= m; j++) fits[j] = fits[j - 1] && second[j - 1] == merged[j - 1];
// [3] Read the letters of the first string one at a time, so fits holds the row for the previous count and becomes the row for this one.
for (int i = 1; i <= n; i++) {
// [4] With no letters of the second string, the merged string must start with the letters of the first string in order.
fits[0] = fits[0] && first[i - 1] == merged[i - 1];
// [5] Letter i + j of the merged string came from the first string, which fits[j] still holds from the previous row, or from the second string, which fits[j - 1] holds in this row. Each needs its letter to match.
for (int j = 1; j <= m; j++) {
fits[j] = (fits[j] && first[i - 1] == merged[i + j - 1]) || (fits[j - 1] && second[j - 1] == merged[i + j - 1]);
}
}
// [6] The corner says whether both strings, used completely, make the whole merged string.
return fits[m];
}function isInterleaving(first, second, merged) {
const n = first.length;
const m = second.length;
// [1] The merged string must hold exactly the letters of both strings, so the lengths must add up.
if (n + m !== merged.length) return false;
// [2] fits[j] says whether the first i letters of one string and the first j letters of the other can make the first i + j letters of the merged string. Before any letter of the first string is read, only the second string is used, and each step needs its letter to match.
const fits = new Array(m + 1).fill(false);
fits[0] = true;
for (let j = 1; j <= m; j++) fits[j] = fits[j - 1] && second[j - 1] === merged[j - 1];
// [3] Read the letters of the first string one at a time, so fits holds the row for the previous count and becomes the row for this one.
for (let i = 1; i <= n; i++) {
// [4] With no letters of the second string, the merged string must start with the letters of the first string in order.
fits[0] = fits[0] && first[i - 1] === merged[i - 1];
// [5] Letter i + j of the merged string came from the first string, which fits[j] still holds from the previous row, or from the second string, which fits[j - 1] holds in this row. Each needs its letter to match.
for (let j = 1; j <= m; j++) {
fits[j] = (fits[j] && first[i - 1] === merged[i + j - 1]) || (fits[j - 1] && second[j - 1] === merged[i + j - 1]);
}
}
// [6] The corner says whether both strings, used completely, make the whole merged string.
return fits[m];
}For ace, bd and abcde it returns true. For ab, c and bac it returns false, because b cannot come before a.
Exercise · Find the bug: The first string forgets its start. This function says whether merged is made by mixing first and second, keeping the order in each. It sometimes says yes when letters of first are out of place. Which line is wrong?
def is_interleaving(first, second, merged):
n, m = len(first), len(second)
if n + m != len(merged):
return False
fits = [False] * (m + 1)
fits[0] = True
for j in range(1, m + 1):
fits[j] = fits[j - 1] and second[j - 1] == merged[j - 1]
for i in range(1, n + 1):
fits[0] = first[i - 1] == merged[i - 1]
for j in range(1, m + 1):
fits[j] = (fits[j] and first[i - 1] == merged[i + j - 1]) or (fits[j - 1] and second[j - 1] == merged[i + j - 1])
return fits[m]A table can also have one string on both sides. A cell is a piece of the string, from i to j. Here is the longest palindromic subsequence of every piece of ababc.
| start \ end | 0 (a) | 1 (b) | 2 (a) | 3 (b) | 4 (c) |
|---|---|---|---|---|---|
| 4 (c) | 1 | ||||
| 3 (b) | 1 | 1 | |||
| 2 (a) | 1 | 1 | 1 | ||
| 1 (b) | 1 | 1 | 3 | 3 | |
| 0 (a) | 1 | 1 | 3 | 3 | 3 |
A piece reads the piece inside it, one step in from each end, and the pieces that drop one end. So the starts run from the last letter to the first, and the ends run upwards. This code does it with one row.
def longest_palindromic_subsequence(text):
n = len(text)
# [1] below is the row for the start i + 1: below[j] is the longest palindromic subsequence of text[i + 1..j]. Before the last start is read, the row is empty and holds 0.
below = [0] * n
# [2] Starts run from the last letter to the first, so the row below is ready when a row reads it.
for i in range(n - 1, -1, -1):
# [3] row[j] will hold the answer for the piece from i to j. A piece of one letter is a palindrome of length 1.
row = [0] * n
row[i] = 1
# [4] Ends run upwards from i + 1, so row[j - 1] is ready when row[j] reads it.
for j in range(i + 1, n):
# [5] If the end letters match, they wrap the best answer for the piece inside, and add 2. If they differ, one end is left out: take the larger of dropping the start (below[j]) and dropping the end (row[j - 1]).
if text[i] == text[j]:
row[j] = below[j - 1] + 2
else:
row[j] = max(below[j], row[j - 1])
# [6] The row just built becomes the row below for the next start.
below = row
# [7] The last cell of the first row is the answer for the whole text.
return below[n - 1]class Solution {
public int longestPalindromicSubsequence(String text) {
int n = text.length();
// [1] below is the row for the start i + 1: below[j] is the longest palindromic subsequence of text[i + 1..j]. Before the last start is read, the row is empty and holds 0.
int[] below = new int[n];
// [2] Starts run from the last letter to the first, so the row below is ready when a row reads it.
for (int i = n - 1; i >= 0; i--) {
// [3] row[j] will hold the answer for the piece from i to j. A piece of one letter is a palindrome of length 1.
int[] row = new int[n];
row[i] = 1;
// [4] Ends run upwards from i + 1, so row[j - 1] is ready when row[j] reads it.
for (int j = i + 1; j < n; j++) {
// [5] If the end letters match, they wrap the best answer for the piece inside, and add 2. If they differ, one end is left out: take the larger of dropping the start (below[j]) and dropping the end (row[j - 1]).
if (text.charAt(i) == text.charAt(j)) {
row[j] = below[j - 1] + 2;
} else {
row[j] = Math.max(below[j], row[j - 1]);
}
}
// [6] The row just built becomes the row below for the next start.
below = row;
}
// [7] The last cell of the first row is the answer for the whole text.
return below[n - 1];
}
}int longestPalindromicSubsequence(string text) {
int n = text.size();
// [1] below is the row for the start i + 1: below[j] is the longest palindromic subsequence of text[i + 1..j]. Before the last start is read, the row is empty and holds 0.
vector<int> below(n, 0);
// [2] Starts run from the last letter to the first, so the row below is ready when a row reads it.
for (int i = n - 1; i >= 0; i--) {
// [3] row[j] will hold the answer for the piece from i to j. A piece of one letter is a palindrome of length 1.
vector<int> row(n, 0);
row[i] = 1;
// [4] Ends run upwards from i + 1, so row[j - 1] is ready when row[j] reads it.
for (int j = i + 1; j < n; j++) {
// [5] If the end letters match, they wrap the best answer for the piece inside, and add 2. If they differ, one end is left out: take the larger of dropping the start (below[j]) and dropping the end (row[j - 1]).
if (text[i] == text[j]) {
row[j] = below[j - 1] + 2;
} else {
row[j] = max(below[j], row[j - 1]);
}
}
// [6] The row just built becomes the row below for the next start.
below = row;
}
// [7] The last cell of the first row is the answer for the whole text.
return below[n - 1];
}function longestPalindromicSubsequence(text) {
const n = text.length;
// [1] below is the row for the start i + 1: below[j] is the longest palindromic subsequence of text[i + 1..j]. Before the last start is read, the row is empty and holds 0.
let below = new Array(n).fill(0);
// [2] Starts run from the last letter to the first, so the row below is ready when a row reads it.
for (let i = n - 1; i >= 0; i--) {
// [3] row[j] will hold the answer for the piece from i to j. A piece of one letter is a palindrome of length 1.
const row = new Array(n).fill(0);
row[i] = 1;
// [4] Ends run upwards from i + 1, so row[j - 1] is ready when row[j] reads it.
for (let j = i + 1; j < n; j++) {
// [5] If the end letters match, they wrap the best answer for the piece inside, and add 2. If they differ, one end is left out: take the larger of dropping the start (below[j]) and dropping the end (row[j - 1]).
if (text[i] === text[j]) {
row[j] = below[j - 1] + 2;
} else {
row[j] = Math.max(below[j], row[j - 1]);
}
}
// [6] The row just built becomes the row below for the next start.
below = row;
}
// [7] The last cell of the first row is the answer for the whole text.
return below[n - 1];
}For ababc it returns 3. For abdbca it returns 5.
Look for one or two strings, a question about prefixes or pieces, and a choice at the last letters. Then ask which neighbours the choice reads.
| Problem | Strings | Cell holds | Reads |
|---|---|---|---|
| Count palindromic pieces | One, pieces | Flag, then a count | The piece inside |
| Interleaving | Two and a third | Flag | Above or left, with a matching letter |
| Longest palindromic subsequence | One, pieces | A length | The piece inside, or a piece with one end moved |
| Edit distance | Two | A count of edits | Diagonal, above and left |
| Fewest deletions | Two | A count of deletions | Above and left |
| Ways a pattern appears | Two | A count | The same row and the diagonal, going downwards |
| Wildcard matching | Two, with a star | Flag | A star reads above or left |
A row reads only the row above and the cell to its left, so two rows are enough. For two strings of 1,000 letters that is 2,002 numbers instead of 1,002,001. To rebuild the edits, as a spell-checker does, keep the whole table and walk back from the last cell.
Predict what happens
Q In the table for the pieces of ababc, the piece from 0 to 4 compares a and c. They differ. Which cells does it read?
Answer: B
The ends differ, so one of them cannot be kept. The best answer is the larger of the piece without the first letter and the piece without the last letter.
Predict what happens
Q The edit table for cat and cart is filled with the first row and column set to 0 instead of counting insertions and deletions. What goes wrong?
Answer: B
The first row holds the insertions from nothing and the first column the deletions to nothing. With zeros, an edit that is really needed is counted as free, so the answer is too small.
Now write it yourself. The lab has one function, fewest_edits(source, target, allow_replace). It returns the fewest edits that turn source into target. An edit inserts or deletes a letter, and with allow_replace true it may also replace one.
Here is a small run for cat and cart, with a replace allowed.
| source \ target | (none) | c | a | r | t |
|---|---|---|---|---|---|
| (none) | 0 | 1 | 2 | 3 | 4 |
| c | 1 | 0 | 1 | 2 | 3 |
| a | 2 | 1 | 0 | 1 | 2 |
| t | 3 | 2 | 1 | 1 | 1 |
The answer is 1: insert r. With allow_replace false the answer is also 1, because inserting is not a replace. For lemon and melon the two answers differ: 2 and 4.
Three rules keep it correct:
i letters of the source into the first j of the target". Say it before you write the loop.0, 1, 2, ... and each new row starts with its row number. Never fill them with 0.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
The cost of a table over two strings is the number of cells times the reads for each cell.
| Question | Try every edit | Table over two prefixes |
|---|---|---|
| Time | Grows more than five times with each letter added to both words | O(n × m): one cell for each pair of prefix lengths, with 3 reads |
| Steps for two words of 10 letters, no letter shared | 12,146,179 calls | 121 cells |
| Memory | O(n + m): the path of edits | O(m): two rows |
| Why the answer is right | Every sequence of edits is tried | Each cell reads cells that are already right |
For two strings of 1,000 letters the table has 1,002,001 cells, and two rows hold 2,002 numbers.
Use it when you compare two sequences, or the pieces of one, and the answer for the whole is built from answers for shorter prefixes. Typical questions are the fewest edits, the longest common part, whether one string is a mix of two, and counting how a pattern appears. Strings of a few thousand letters are fine.
Two strings of 100,000 letters need 10,000,000,000 cells, which is too slow. When you only need to know whether a short word appears inside a long text, scanning with a prefix function or hashing is faster. When only a few edits are allowed, a band of cells around the diagonal is enough.
1 + min(prev[j], cur[j - 1]) on a mismatch has no diagonal cell, so a changed letter costs a delete and an insert. For a and b it returns 2, but one replace makes a into b, so the answer is 1.
Without the diagonal cell, a changed letter costs a delete and an insert, so turning a into b costs two edits instead of one.
prev = [0] * (m + 1) and cur[0] = 0 treat the insertions and deletions as free. For b and bb the table returns 0, but one insert is needed, so the answer is 1. The first row is 0, 1, 2, ... and each new row starts with i.
cur[j] = 1 + min(prev[j - 1], prev[j], cur[j - 1]) for every cell charges one edit for letters that already match. For b and b it returns 1, and the answer is 0. Equal letters copy the diagonal.
for i in range(n) for a table over the pieces of one string reads the row for i + 1 before it is built. For aca it returns 2, and the answer is 3. The starts must run from the last letter to the first.
lemon and melon they are 3, 4 and 2.Explain the three neighbours in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The cell rule
Q In the edit distance table, which cells does a cell read when the two last letters differ?
Answer: A
A mismatch gives three choices: replace (the diagonal), delete (above) and insert (left). The cell is 1 plus the smallest of the three.
Checkpoint · Equal letters
Q The last letters of the two prefixes are equal. What does the edit distance cell hold?
Answer: A
Equal letters need no edit, so the answer is the diagonal cell. Adding 1 would charge for letters that already match.
Checkpoint · The first row and column
Q What are the first row and the first column of the edit distance table?
Answer: A
Turning nothing into j letters takes j insertions, and i letters into nothing takes i deletions. Zeros would make those edits free.
Checkpoint · One table, three answers
Q For lemon and melon the longest common subsequence has 3 letters. How many deletions, from both words, make them equal?
Answer: A
Keep the common letters and delete the rest of both words: 5 + 5 - 2 × 3 = 4. A replace is not allowed, so it is more than the edit distance 2.
Checkpoint · Edit distance and deletions
Q Allowing a replace changes the answer for lemon and melon from 4 to what?
Answer: A
Lemon becomes melon with two replaces: l to m and m to l. Without replaces it needs four inserts and deletes.
Checkpoint · The order of filling
Q A cell of a table over two words reads the cell above, the cell to the left and the diagonal. How is the table filled?
Answer: A
Each cell reads three cells that are above or to the left. Filling row by row, left to right, makes all three ready.
Checkpoint · One string, pieces
Q A table over the pieces of one string reads the piece inside, from i + 1 to j - 1. How are the starts filled?
Answer: A
A piece from i reads pieces that start at i + 1. Those rows must be filled first, so the starts run from the last letter to the first.
Checkpoint · Interleaving
Q To check whether a third string mixes two strings in order, which cells does a cell read?
Answer: A
The last letter of the third string came from one of the two strings. That is the cell above, or the cell to the left, and the letter must match.
Checkpoint · The cost
Q Two strings have 1,000 letters each. How many cells does the table have, and how many numbers do two rows hold?
Answer: A
There is one cell for each pair of prefix lengths: 1,001 × 1,001 = 1,002,001. Two rows of 1,001 numbers need 2,002.
Checkpoint · When it does not fit
Q Two strings have 100,000 letters each. What goes wrong with the table?
Answer: A
The table has one cell for each pair of positions: about 10,000,000,000 cells for 100,000 letters on each side. A different method is needed.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.