Edit Distance
Intuition
How many single-character edits turn "kitten" into "sitting"? Substitute k→s, substitute e→i, insert g: three. The smallest such number is the Levenshtein distance.
Precise explanation
Let be the distance between the first characters of and the first of :
(deletion, insertion, substitution/match). The answer is . Time ; only two rows are needed for memory .
| "" | s | i | t | |
|---|---|---|---|---|
| "" | 0 | 1 | 2 | 3 |
| k | 1 | 1 | 2 | 3 |
| i | 2 | 2 | 1 | 2 |
| t | 3 | 3 | 2 | 1 |
Table: D for "kit" → "sit": distance 1.
Worked example
levenshtein("kitten", "sitting") = 3; levenshtein("", "abc") = 3.
Common mistakes
- Forgetting the first row/column initialisation.
- Off-by-one between string index and table index (
a[i-1]). - Exponential recursion without memoisation.
Why this matters
Edit distance powers spelling correction, fuzzy matching and evaluation metrics such as word error rate in speech recognition.
References
- Speech and Language Processing (3rd ed. draft) — Dan Jurafsky, James H. Martin (
S017)