Edit distance (Levenshtein)
How many insertions, deletions and substitutions separate two strings? Dynamic programming on a 2D table, then saving memory down to a single row.
A CLI suggests "Did you mean commit?" when someone types comit. Such suggestions (and spell checkers, DNA sequence comparison or typo-squatting detection in package names) rely on the Levenshtein edit distance: the smallest number of single-character operations that turn one string into another.
Task
Return the edit distance between strings a and b. Allowed operations, each costing 1:
- inserting a character,
- deleting a character,
- substituting a character with another.
Signatures: editDistance(a, b) (JS/TS), edit_distance(a, b) (Python), Solution.EditDistance (C#), Solution.editDistance (Java), EditDistance (Go).
Examples
a | b | Result | Operations |
|---|---|---|---|
"kitten" | "sitting" | 3 | k→s, e→i, +g |
"flaw" | "lawn" | 2 | −f, +n |
"intention" | "execution" | 5 | |
"" | "abc" | 3 | three insertions |
"same" | "same" | 0 |
Constraints
0 ≤ a.length, b.length ≤ 1,000, ASCII characters.
Expected complexity
O(m · n) time, O(min(m, n)) memory (the two-row version; the full O(m · n) table passes the tests too).