Problem overview
The method minDistance receives two strings, word1 and word2, and returns the fewest operations that turn word1 into word2. There are three operations, each costing one: insert a character anywhere, delete a character, or replace a character with another one. Both words use lowercase letters and either can be empty, with at most 500 characters each.
For "horse" and "ros" the answer is 3: replace h with r to get "rorse", delete the second r to get "rose", and delete e to get "ros". Two operations can't do it, because the words differ by two characters in length, so both would have to be deletes, and deleting letters from "horse" never gives "ros". For "" and "abc" the answer is 3, three inserts.
Approach: a table of prefix answers
Trying every sequence of operations is far too slow. Solve smaller versions of the problem and build up. Let dp[i][j] be the fewest operations that turn the first i characters of word1 into the first j characters of word2. With m and n the two lengths, the table has (m + 1) × (n + 1) entries, and the answer is dp[m][n].
Row 0 and column 0 stand for an empty prefix. Turning i characters into nothing takes i deletes, so dp[i][0] = i. Turning nothing into j characters takes j inserts, so dp[0][j] = j.
For every other entry, look at the last characters of the two prefixes, word1[i - 1] and word2[j - 1]. The prefix of length i ends at index i - 1, because the string counts from 0 while the table counts characters.
- They are equal. They need no operation, so
dp[i][j] = dp[i - 1][j - 1]. Spending an operation on either of them is never better. - They differ. One operation must fix the end, and the entry is 1 plus the smallest of three neighbours:
dp[i - 1][j - 1]for a replace: both prefixes lose their last character.dp[i - 1][j]for a delete ofword1's last character: onlyword1's prefix gets shorter.dp[i][j - 1]for an insert ofword2's last character at the end: it matches that character, so onlyword2's prefix gets shorter.
Filling the table row by row and left to right means the three neighbours are always known before they are needed. For "horse" and "ros" the table is below. Rows go with the prefixes of "horse" from empty to the whole word, and columns with the prefixes of "ros":
0 1 2 3
1 1 2 3
2 2 1 2
3 2 2 2
4 3 3 2
5 4 4 3
The bottom right entry, 3, is the answer.
Step by step
- Store the lengths in
mandn. Both come up often in the loops. - Create
dpas anumber[][]withm + 1rows ofn + 1zeros.Array.from({ length: m + 1 }, ...)calls its function once per row, and each call returns a freshnew Array(n + 1).fill(0). - Fill column 0 with a loop for
ifrom 0 tom, settingdp[i][0] = i:ideletes. - Fill row 0 with a loop for
jfrom 0 ton, settingdp[0][j] = j:jinserts.dp[0][0]is set twice, both times to 0. - Loop over the rest of the table,
ifrom 1 tomand, inside it,jfrom 1 ton. Row 0 and column 0 are already filled. - Equal last characters: copy the diagonal,
dp[i][j] = dp[i - 1][j - 1]. - Different last characters: this is the key line. Set
dp[i][j]to 1 plus theMath.minof the replace, delete and insert neighbours.Math.minaccepts any number of arguments. - Return
dp[m][n], the answer for both whole words.
The solution in TypeScript
class Solution {
minDistance(word1: string, word2: string): number {
const m = word1.length;
const n = word2.length;
const dp: number[][] = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
for (let i = 0; i <= m; i++) {
dp[i][0] = i;
}
for (let j = 0; j <= n; j++) {
dp[0][j] = j;
}
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
if (word1[i - 1] === word2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1];
} else {
dp[i][j] = 1 + Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][n];
}
}
A few TypeScript details:
- Rows must be separate arrays.
new Array(m + 1).fill(new Array(n + 1).fill(0))would put one row object in every slot, so changing one cell would change it in every row. WithArray.fromand an arrow function, each row is created by its own call. For example, building two rows the shared way and settingshared[0][1] = 9gives[[0,9,0],[0,9,0]]. - Indexing a string.
word1[i - 1]gives a one-character string, and===compares two such strings by value. - Types are erased.
number[][]exists only for the compiler: it is removed when the code is compiled to JavaScript.
Complexity
Time: O(m · n). The table has (m + 1) × (n + 1) entries and each takes a constant amount of work.
Space: O(m · n). The table is kept whole. Each row reads only itself and the row above it, so two rows of n + 1 numbers would be enough and bring the space down to O(n). The whole table is easier to follow, and it is what this lesson uses.
Edge cases and common mistakes
- Empty words.
minDistance("", "abc")is 3,minDistance("abc", "")is 3 andminDistance("", "")is 0. All of them come straight from row 0 and column 0, and the loops over the rest never run when either word is empty. - Off-by-one on the characters. Entry
dp[i][j]is abouticharacters, so the last one isword1[i - 1]. Usingword1[i]compares the wrong characters and reads past the end of the word in the last row. - Forgetting the base row and column. With them left as zeros, every turn into or out of an empty prefix looks free.
- Forgetting the replace. Taking only the insert and delete neighbours counts a replace as two operations. For
"ab"and"ba"the answer is 2 either way, but for"a"and"b"the correct answer is 1 and an insert-plus-delete version gives 2. - Swapping the inner loops' bounds. The outer loop follows
word1and runs tom, and the inner followsword2and runs ton. Mixing them up fails when the words have different lengths.
Testing
"horse"and"ros"give3."intention"and"execution"give5.""and"abc"give3."abc"and"abc"give0."kitten"and"sitting"give3.
