Edit Distance
Find the fewest letter inserts, deletes and replaces that turn one word into another.
Given two strings word1word2word1word2
Example 1
Output: 3
Explanation: replace h with r (rorse), delete r (rose), delete e (ros).
Example 2
Output: 5
Explanation: delete t (inention), replace i with e (enention), replace n with x (exention), replace n with c (exection), insert u (execution).
The Idea
When you type "hrose", a spell checker suggests "horse", because a few small changes turn one word into the other. Each change is one edit: insert a letter, delete a letter, or replace a letter. The fewest edits between two words is called their edit distance, also known as the Levenshtein distance.
Example 1 turns "horse" into "ros" with three edits: replace h with r to get "rorse", delete the second r to get "rose", and delete the e. Could two edits be enough? Going from five letters to three already takes two deletions. But no two deletions from "horse" leave "ros", because in "horse" the r comes after the o.
That check works for a short word. For "intention" and "execution", or two words of a hundred letters, the possible sequences of edits are far too many to try one by one. So where do we start?
Start at the last letters. "horse" ends in e and "ros" ends in s, so the best edits must do something about that e. There are three choices. Delete the e, then turn "hors" into "ros". Or turn "horse" into "ro", then insert s at the end. Or replace the e with s, then turn "hors" into "ro".
Each choice leaves a smaller question of the same kind, about the start of each word. The first few letters of a word, such as "hor" in "horse", are called a prefix. If the last letters were equal, they could simply stay, and only the prefixes before them would matter.
So once the answers for shorter prefixes are known, the answer for the full words is 1 plus the cheapest of the three choices. Look at the picture below. The table has one row for each start of "horse", from (empty) to horse, and one column for each start of "ros". Each cell holds the fewest edits that turn its row's letters into its column's letters.
The corner cell, in row horse and column ros, holds the answer, 3. The cell above it, in row hors, holds 2: delete the e, then turn "hors" into "ros" with 2 more edits. The diagonal cell holds 3 and the cell to the left holds 4, so those two choices would cost 4 and 5. The cheapest is 1 + 2 = 3.
The corner cell could be worked out only because its three neighbours, for shorter prefixes, were already filled. Filling the table from the shortest prefixes, "h" and "r", up to "horse" and "ros", so that each cell reads answers already in the table, is called dynamic programming.
Solution Approach
Turning the table into code means settling four things: why a table beats following the three choices directly, what one cell means, how to fill the first row and column, and the rule and order for every other cell.
Following the three choices directly
Why not write a method that calls itself on the shorter prefixes, once for each of the three choices? It finds the right answer, but every pair of different last letters splits into three calls, and the same pairs of prefixes come up again and again.
From "horse" and "ros", replacing the e leads to "hors" and "ro". Deleting the e and then inserting the s leads there too. Counted in a run, this plain version makes 77 calls for "horse" and "ros", and 1,709 for "intention" and "execution". The table for those pairs has 24 and 100 cells, each filled once.
What one cell means
What exactly does a cell hold? In the code the table is an array named tabletable[i][j]word1word2table[4][2]
Row 0 and column 0 stand for the empty prefix. So if m and n are the lengths of word1word2table[m][n]
The first row and column
What goes in the row and column for the empty prefix? Turning "hor" into nothing takes 3 deletions, so table[3][0]table[i][0]table[0][2]table[0][j]
The rule and order for every other cell
How is any other cell filled? Compare the last letter of each prefix: word1.charAt(i - 1)word2.charAt(j - 1)table[i - 1][j - 1]
If the last letters differ, the cell is 1 plus the smallest of three neighbours. The diagonal one, table[i - 1][j - 1]table[i - 1][j]word1table[i][j - 1]word2
Every cell reads only the cells above it, to its left and up-left. Filling the rows from top to bottom, each from left to right, means those three are always ready when a cell needs them.
Java Solution
The method minDistance
- First,
hands the work tominDistance , which builds and returns the whole table, so thateditTable can print it too.main stores the two lengths ineditTable andm and createsn , antable array with m + 1 rows and n + 1 columns.int- A loop over
setsi , and a second loop overtable[i][0] = i setsj : the deletions and insertions for an empty prefix.table[0][j] = j - The other cells are filled with two loops, one inside the other. The outer loop moves
down the rows from 1 to m, and the inner loop movesi across the columns from 1 to n.j - Inside, if
equalsword1.charAt(i - 1) , the cell copiesword2.charAt(j - 1) . Otherwise the three neighbours go intotable[i - 1][j - 1] ,replace anddelete , and the cell gets 1 plus the smallest of them.insert - Finally,
returns the bottom-right cell,minDistance , the one for both full words.table[m][n]
The main
import java.util.Arrays;
public class EditDistance {
public static int minDistance(String word1, String word2) {
return editTable(word1, word2)[word1.length()][word2.length()];
}
// table[i][j]: fewest edits that turn the first i letters of word1
// into the first j letters of word2
static int[][] editTable(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] table = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) {
table[i][0] = i; // delete all i letters
}
for (int j = 0; j <= n; j++) {
table[0][j] = j; // insert all j letters
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
table[i][j] = table[i - 1][j - 1]; // same last letter: free
} else {
int replace = table[i - 1][j - 1];
int delete = table[i - 1][j];
int insert = table[i][j - 1];
table[i][j] = 1 + Math.min(replace, Math.min(delete, insert));
}
}
}
return table;
}
public static void main(String[] args) {
for (int[] row : editTable("horse", "ros")) {
System.out.println(Arrays.toString(row));
}
System.out.println(minDistance("horse", "ros"));
System.out.println(minDistance("intention", "execution"));
System.out.println(minDistance("abc", ""));
System.out.println(minDistance("", "abc"));
System.out.println(minDistance("same", "same"));
System.out.println(minDistance("abc", "xyz"));
}
}
Running it prints:
[0, 1, 2, 3]
[1, 1, 2, 3]
[2, 2, 1, 2]
[3, 2, 2, 2]
[4, 3, 3, 2]
[5, 4, 4, 3]
3
5
3
3
0
3
The six bracketed lines are the table from the picture, one per start of "horse". The fifth, [4, 3, 3, 2][5, 4, 4, 3]
"abc" against an empty word prints 3 for three deletions, and the reverse prints 3 for three insertions. "same" against itself prints 0: every letter matches, so each cell on the diagonal copies the 0 from the top-left corner. The last line, 3, is three replaces for "abc" and "xyz", cheaper than three deletions plus three insertions.
The two loops for row 0 and column 0 are easy to leave out, because Java fills a new int
Complexity
The work is filling the table once, with a fixed amount of work per cell.
- Time: O(m × n), because each of the m × n cells outside row 0 and column 0 does one letter comparison and at most two
calls.Math.min - Space: O(m × n), because
keeps (m + 1) × (n + 1) numbers. Each row reads only itself and the row above, so when only the answer is needed, two rows of n + 1 numbers are enough.table
If only deletions are allowed, from either word, the fewest edits follow from the