358. Compute Levenshtein edit distance
Spell checkers, fuzzy matching and word error rate for speech models all use edit distance: the fewest single-character inserts, deletes and substitutions to turn one string into another.
Write edit_distance(a, b) with dynamic programming. Each operation costs 1.
def edit_distance(a, b)Example 1
Input: a = 'kitten', b = 'sitting'
Output: 3
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
The distance between two prefixes can be built from the distances of slightly shorter prefixes, which makes this a dynamic programming table.
Hint 2
Let dp[i][j] be the distance between a[:i] and b[:j], start the first row and column with 0, 1, 2, ..., and fill each cell as the cheapest of delete, insert or substitute.
Hint 3
The cell rule is min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + (a[i-1] != b[j-1])), and you can keep only the previous row to save memory.
Common mistakes
- Comparing position by position (the buggy version) cannot handle an insertion, which shifts everything after it.
Understand the idea
Edit distance counts the fewest single-character inserts, deletes and substitutions needed to turn one string into another. Comparing position by position fails as soon as one character is inserted, because everything after it shifts. Dynamic programming fixes this: build a table where D[i][j] is the distance between the first i characters of a and the first j of b, and fill it from smaller prefixes.
a = 'cat', b = 'cart'. Position by position, 't' vs 'r' and then a missing letter look like 2 changes, but the true answer is 1: insert 'r'. Small table for 'ab' to 'b': D[0][j] = j and D[i][0] = i. D[1][1] ('a' vs 'b') = 1. D[2][1] ('ab' vs 'b'): last characters match, so D[1][0] = 1. Answer 1 (delete 'a').
D[i][j] = min(D[i-1][j] + 1, D[i][j-1] + 1, D[i-1][j-1] + (0 if a_i == b_j else 1))
Spell checkers and word error rate for speech models use this.