Levenshtein Edit Distance
Background
Levenshtein distance is the minimum number of single-character insertions, deletions, and substitutions to turn one string into another. Foundational primitive for spell-check, fuzzy matching, DNA alignment, and the classic dynamic-programming exercise. time and space.
Problem statement
Implement levenshtein(a, b) via the canonical 2-D DP:
Return dp[len(a)][len(b)].
Input
a—str.b—str.
Output
Returns int >= 0, the edit distance.
Examples
Example 1 — classic worked example
Input: a="kitten", b="sitting"
Output: 3
Explanation: kitten → sitten (sub k→s) → sittin (sub e→i) → sitting (insert g). Three edits.
Example 2 — identical strings
Input: a="abc", b="abc"
Output: 0
Example 3 — empty cases
Input: a="", b="abc" → 3
Input: a="abc", b="" → 3
Input: a="", b="" → 0
Example 4 — single substitution
Input: a="cat", b="bat"
Output: 1
Example 5 — insertion at the end
Input: a="abc", b="abcd"
Output: 1
Constraints
- Allowed edits: insert, delete, substitute (all cost 1).
- Empty inputs return the length of the other string.
- time and space is acceptable.
Notes
- Space optimisation. You only need the previous row of the DP table; that drops memory to .
- Variants. Damerau-Levenshtein adds a transposition operation; Hamming forbids insertion/deletion (only substitutions). Same DP shape, different recurrence.
▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.
- •Classic worked example: kitten -> sitting
- •Reference pair: sunday -> saturday
- •Sample overlap: flaw -> lawn