Edit distance

How many changes separate 2 words · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Edit distance

Edit distance, or Levenshtein distance, is the fewest changes needed to turn one text into another. There are 3 possible changes: insert a letter, delete a letter or replace a letter with another. From «kitten» to «sitting» there are 3: 2 replacements and 1 insertion. It is used in search engines and language processing to measure how similar 2 texts are, like correcting «hlelo» to «hello».

To split the problem you look at the last letters of s and t. If they match, both are skipped and you move on to the earlier ones. If not, s is edited so they match, and you also move on. The state is [i, j]: how many letters of s and of t are left to resolve. dp[i, j] is the fewest changes to turn the first i letters of s into the first j of t. With s of n letters and t of m, the table has (n + 1) × (m + 1) cells.

When s[i − 1] and t[j − 1] are the same letter, no change is needed: both are skipped and dp[i, j] = dp[i − 1, j − 1]. That is why «cat» and «bat» are only 1 edit apart: the a and the t match and add nothing. Forgetting this case would give distances that are too large: treating each matching letter as a replacement would add 1 for each.

dp[i, j] depends on up, left and up-left. With a single row, going forward overwrites the up-left value, and going backward does not have the left one in time. The fix is to keep the up-left value in a variable, leftup, and walk forward. That lowers memory from O(nm) to O(m). The time is still O(nm): with 2 texts of 1,000 letters, 1 million cells.

State transition equation

If s[i − 1] and t[j − 1] do not match, there are 3 options. Insert t[j − 1] after s[i − 1]: dp[i, j − 1] is left. Delete s[i − 1]: dp[i − 1, j] is left. Replace s[i − 1] with t[j − 1]: dp[i − 1, j − 1] is left. The cheapest is chosen and 1 is added: dp[i, j] = min(dp[i, j − 1], dp[i − 1, j], dp[i − 1, j − 1]) + 1. Each cell looks left, up and up-left.

Dynamic programming

If both texts are empty, the distance is 0: dp[0, 0] = 0. If s is empty and t is not, every letter of t must be inserted: dp[0, j] = j. If t is empty and s is not, every letter of s must be deleted: dp[i, 0] = i. Since each cell looks left, up and up-left, the table is filled with 2 forward for loops, row by row.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

How many changes separate 2 words