1. Levenshtein Distance
The edit distance that powers spell checkers, DNA alignment, and fuzzy search
You mistype "recieve" and your editor instantly suggests "receive." Your search engine understands "pythn" means "python." A biologist aligns two DNA sequences to find where they diverge. All of these rely on the same idea: how many single-character edits does it take to turn one string into another?
That count is the Levenshtein distance, named after Soviet mathematician Vladimir Levenshtein who defined it in 1965. It's one of the most widely used algorithms in computer science -- and the classic introduction to dynamic programming.
The Three Operations
Levenshtein distance allows exactly three operations, each costing 1 edit:
| Operation | Example | Description |
|---|---|---|
| Insert | cat -> cart |
Add a character at any position |
| Delete | cart -> cat |
Remove a character from any position |
| Replace | cat -> cut |
Swap one character for another |
The Levenshtein distance between two strings is the minimum number of these operations needed to transform one into the other.
A Simple Example
Source: kitten → Target: sitting
kitten
sitten (replace k → s) cost: 1
sittin (replace e → i) cost: 2
sitting (insert g at end) cost: 3
Levenshtein distance = 3. No sequence of fewer edits can do it.
With short strings, you can find the answer by inspection. But how do you prove it's optimal -- and how do you handle strings that are hundreds of characters long?
The Recursive Insight
Compare two strings a (length m) and b (length n)
character by character, starting from the end. At each step, there are only two possibilities:
The Core Recurrence
If the last characters match (a[m-1] == b[n-1]), the distance is the same
as for the strings with those characters removed -- no edit needed.
If they don't match, try all three operations and take the cheapest:
- Insert: solve for
a[0..m]vsb[0..n-1], then + 1 - Delete: solve for
a[0..m-1]vsb[0..n], then + 1 - Replace: solve for
a[0..m-1]vsb[0..n-1], then + 1
Pseudocode (Recursive)
function lev(a, b, i, j):
if i == 0: return j // insert all of b
if j == 0: return i // delete all of a
if a[i-1] == b[j-1]:
return lev(a, b, i-1, j-1)
return 1 + min(
lev(a, b, i, j-1), // insert
lev(a, b, i-1, j ), // delete
lev(a, b, i-1, j-1) // replace
)
This works, but it's exponentially slow. For "kitten" vs "sitting", the recursive tree makes hundreds of calls -- and most of them compute the same subproblems over and over.
Why Recursion Explodes
Overlapping subproblems
lev("kit", "sit")
├── lev("ki", "sit") ← insert
│ ├── lev("k", "sit")
│ ├── lev("ki", "si") ← ★
│ └── lev("k", "si")
├── lev("kit", "si") ← delete
│ ├── lev("ki", "si") ← ★ (same subproblem!)
│ ├── lev("kit", "s")
│ └── lev("ki", "s")
└── lev("ki", "si") ← ★ (again!)
└── ...
The same subproblem lev("ki", "si") appears three times in this tiny
fragment. In the full tree, the redundancy is catastrophic. The time complexity is
O(3max(m,n)).
The fix is dynamic programming: solve each subproblem once, store the result, and look it up whenever it's needed again.
The Dynamic Programming Table
Build an (m+1) x (n+1) table where cell [i][j] holds the
Levenshtein distance between the first i characters of a and the
first j characters of b.
-
Initialize the borders
Row 0: transforming "" into
b[0..j]costsjinserts.
Column 0: transforminga[0..i]into "" costsideletes. -
Fill left-to-right, top-to-bottom
For each cell
[i][j], ifa[i-1] == b[j-1], copy the diagonal:dp[i][j] = dp[i-1][j-1].
Otherwise:dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]). -
Read the answer
The bottom-right cell
dp[m][n]is the Levenshtein distance.
Worked Example: "kitten" → "sitting"
The completed DP table
"" 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
The bottom-right cell is 3 -- confirming the answer we found by hand.
Let's trace how a few cells were filled:
Cell [2][2]: comparing "ki" vs "si"
a[1] = 'i', b[1] = 'i' → they match!
dp[2][2] = dp[1][1] = 1 (copy diagonal)
Cell [1][1]: comparing "k" vs "s"
a[0] = 'k', b[0] = 's' → mismatch
dp[1][1] = 1 + min(
dp[0][1], // insert: 1
dp[1][0], // delete: 1
dp[0][0] // replace: 0 ← smallest
) = 1 + 0 = 1
Cell [6][7]: comparing "kitten" vs "sitting"
a[5] = 'n', b[6] = 'g' → mismatch
dp[6][7] = 1 + min(
dp[5][7], // insert: 4
dp[6][6], // delete: 2
dp[5][6] // replace: 3
) = 1 + 2 = 3
The Complete Algorithm
function levenshtein(a, b):
m = length(a)
n = length(b)
// Create (m+1) x (n+1) table
dp = new array[m+1][n+1]
// Base cases
for i from 0 to m: dp[i][0] = i
for j from 0 to n: dp[0][j] = j
// Fill the table
for i from 1 to m:
for j from 1 to n:
if a[i-1] == b[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = 1 + min(
dp[i-1][j], // delete
dp[i][j-1], // insert
dp[i-1][j-1] // replace
)
return dp[m][n]
Complexity
Time: O(m x n) -- we fill every cell exactly once.
Space: O(m x n) for the full table, or O(min(m, n))
if you only keep two rows at a time (since each row depends only on the previous one).
Backtracking: What Were the Actual Edits?
The DP table tells you the cost, but not which operations to perform.
To recover the edit sequence, trace backward from dp[m][n] to
dp[0][0], following the path of minimum cost:
Backtracking "kitten" → "sitting"
dp[6][7] = 3 ← came from dp[6][6] + 1 (insert 'g')
dp[6][6] = 2 ← came from dp[5][5] + 1 (replace 'e' → 'i')
dp[5][5] = 2 ← came from dp[4][4] (match 't') -- no, wait...
Let's trace more carefully:
dp[6][7]=3 ← dp[5][7]=4, dp[6][6]=2, dp[5][6]=3 → min is dp[6][6]=2 (delete)
dp[6][6]=2 ← dp[5][5]=2 (match 'n'='n', copy diagonal)
dp[5][5]=2 ← dp[4][4]=1, dp[5][4]=2, dp[4][5]=2 → came from dp[4][4]+1 (replace 'e'→'i')
dp[4][4]=1 ← dp[3][3]=1 (match 't'='t')
dp[3][3]=1 ← dp[2][2]=1 (match 't'='t')
dp[2][2]=1 ← dp[1][1]=1 (match 'i'='i')
dp[1][1]=1 ← dp[0][0]=0 +1 (replace 'k'→'s')
dp[0][0]=0 ← done!
Edits: replace k→s, replace e→i, insert g
Where Levenshtein Distance Is Used
| Application | How it uses edit distance |
|---|---|
| Spell checking | Suggest words within distance 1 or 2 of the mistyped word |
| Fuzzy search | Match query to database entries allowing for typos |
| DNA sequence alignment | Find how two genetic sequences differ (with weighted operations) |
| Diff tools | Compute the minimum set of changes between two files |
| Autocorrect | Rank correction candidates by edit distance from the typed word |
| Record linkage | Match "Jon Smith" to "John Smith" across databases |
Variations and Extensions
Levenshtein distance is the simplest member of a family of edit distance metrics. Here are the most common variations:
Damerau-Levenshtein
Adds a fourth operation: transposition (swapping two adjacent characters). Catches "teh" → "the" in one edit instead of two.
Longest Common Subsequence
Only allows inserts and deletes (no replacements). The "diff" you see in version control is based on LCS.
Weighted Edit Distance
Assign different costs to different operations or character pairs. In DNA, a transition mutation might cost less than a transversion.
Key Takeaways
- Levenshtein distance counts the minimum insertions, deletions, and replacements to transform one string into another
- The naive recursive solution has exponential time due to overlapping subproblems
- Dynamic programming solves it in O(m x n) time by filling a 2D table bottom-up
- Each cell depends on three neighbors: left, above, and diagonal -- representing the three edit operations
- Backtracking through the table recovers the actual edit sequence
- It's the foundation for spell checkers, fuzzy search, DNA alignment, and diff tools
Try It Yourself -- Levenshtein Distance
Type two strings to see the DP table fill in real time. Cells on the optimal path are highlighted, and the edit sequence is shown below.
Distance: --
Edit Sequence
Levenshtein distance is a beautiful introduction to dynamic programming -- the idea that you can solve a big problem by combining answers to smaller subproblems you've already solved. This pattern shows up everywhere in algorithm design, from shortest paths to sequence alignment to parsing.