Edit Distance

Find the fewest letter inserts, deletes and replaces that turn one word into another.

Given two strings word1 and word2, return the fewest operations that turn word1 into word2. Each operation changes one character: insert a character, delete a character, or replace a character with another one.

Example 1
Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: replace h with r (rorse), delete r (rose), delete e (ros).
Example 2
Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: delete t (inention), replace i with e (enention), replace n with x (exention), replace n with c (exection), insert u (execution).
Solution

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 edit table for horse and ros. Rows are the starts of horse, from empty to horse; columns are the starts of ros. The corner cell, 3, is 1 plus the smallest of its three neighbours: diagonal 3 for a replace, above 2 for a delete, left 4 for an insert.

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 table, and table[i][j] is the fewest edits that turn the first i letters of word1 into the first j letters of word2. With "horse" and "ros", table[4][2] is the cell for "hors" and "ro", and it holds 3.

Row 0 and column 0 stand for the empty prefix. So if m and n are the lengths of word1 and word2, the table has m + 1 rows and n + 1 columns, and the answer sits in table[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] is 3, and in general table[i][0] is i. Turning nothing into "ro" takes 2 insertions, so table[0][2] is 2, and table[0][j] is j. In the picture, that is the 0 to 5 down the (empty) column and the 0 to 3 along the (empty) row.

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) and word2.charAt(j - 1), at position i - 1 because row i holds i letters. If they match, they need no edit, and the cell copies its diagonal neighbour, table[i - 1][j - 1]. In the picture, "ho" and "ro" both end in o, so the cell in row ho and column ro copies the 1 from row h and column r.

If the last letters differ, the cell is 1 plus the smallest of three neighbours. The diagonal one, table[i - 1][j - 1], is a replace. The one above, table[i - 1][j], deletes the last letter of the word1 prefix. The one to the left, table[i][j - 1], inserts the last letter of the word2 prefix.

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 works in these steps:

  1. First, minDistance hands the work to editTable, which builds and returns the whole table, so that main can print it too.
  2. editTable stores the two lengths in m and n and creates table, an int array with m + 1 rows and n + 1 columns.
  3. A loop over i sets table[i][0] = i, and a second loop over j sets table[0][j] = j: the deletions and insertions for an empty prefix.
  4. The other cells are filled with two loops, one inside the other. The outer loop moves i down the rows from 1 to m, and the inner loop moves j across the columns from 1 to n.
  5. Inside, if word1.charAt(i - 1) equals word2.charAt(j - 1), the cell copies table[i - 1][j - 1]. Otherwise the three neighbours go into replace, delete and insert, and the cell gets 1 plus the smallest of them.
  6. Finally, minDistance returns the bottom-right cell, table[m][n], the one for both full words.

The main method prints the table for "horse" and "ros" row by row, then runs both examples, an empty word on each side, a word against itself, and two words with no letter in common.

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

Output
[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], is row hors, and its last value is the 2 that the corner cell builds on. The sixth, [5, 4, 4, 3], ends in the answer for Example 1, which the next line, 3, repeats. Example 2 prints 5.

"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 array with zeros anyway. A separate run of the method without them returned 0 for "abc" and an empty word, and 2 for "horse" and "ros". With zeros there, turning a prefix into an empty one looks free.

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 Math.min calls.
  • Space: O(m × n), because table 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.

If only deletions are allowed, from either word, the fewest edits follow from the Longest Common Subsequence, the most letters that both words contain in the same order, though not always side by side.