Edit Distance (Levenshtein)
Compare two strings and watch the Levenshtein matrix fill in. The final cell is the minimum number of edits needed to transform one string into the other.
| ∅ | s | i | t | t | i | n | g | |
|---|---|---|---|---|---|---|---|---|
| ∅ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| k | 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
| i | 2 | 2 | 1 | 2 | 3 | 4 | 5 | 6 |
| t | 3 | 3 | 2 | 1 | 2 | 3 | 4 | 5 |
| t | 4 | 4 | 3 | 2 | 1 | 2 | 3 | 4 |
| e | 5 | 5 | 4 | 3 | 2 | 2 | 3 | 4 |
| n | 6 | 6 | 5 | 4 | 3 | 3 | 2 | 3 |
This cell kitten → sitting: 3
Characters differ: choose the cheapest operation.
Distance: 3
A diagonal move is a match (cost 0) or a replace (cost 1). Horizontal and vertical moves are insert and delete. The highlighted path is one optimal edit sequence. Edit either word to turn this into a reusable tool; ties prefer the diagonal.
What you are seeing
Rows and columns are prefixes of the two strings. Each cell stores the edit distance between those prefixes.
If the current characters match, the diagonal value carries over. If not, take one plus the minimum of insert, delete, and replace.
The bottom-right cell is the answer. Backtracking reveals the actual edit sequence.
Why it matters
Edit distance powers spell checkers, DNA alignment, fuzzy search, and diff tools. It is also a clean example of 2D dynamic programming.
Complexity & details
Time: O(mn), space: O(mn) for the full matrix (O(min(m,n)) with rolling rows).
Frequently asked questions
What counts as one edit?+
Inserting one character, deleting one character, or replacing one character. Substituting a character is one replace operation.
Where is edit distance used?+
Spell correction, DNA sequence alignment, plagiarism detection, fuzzy matching, and version-control diffs all use variants of edit distance.