Edit distance (Levenshtein, recursion)
Hard TimeO(3^(m+n)) naive; O(m·n) memoised SpaceO(m + n) stack
Return the fewest single-character edits — insert, delete or substitute — that turn one string into another. "cat" to "cut" takes 1. Each edit costs one wherever it is applied, turning a string into itself costs nothing, and turning any string into an empty one costs its length.
Examples
Example 1
- Input
- a = 'cat'b = 'cut'i = 0j = 0
- Output
- One substitution,
1aforu; thecand thetalready match.
Example 2
- Input
- a = 'cat'b = ''i = 0j = 0
- Output
- Three characters to delete, and nothing cheaper exists — the cost is the length.
3
The Code
function editDistance(a, b, i, j) {
if (i === a.length) return b.length - j;
if (j === b.length) return a.length - i;
if (a[i] === b[j]) return editDistance(a, b, i + 1, j + 1);
const insert = editDistance(a, b, i, j + 1);
const remove = editDistance(a, b, i + 1, j);
const replace = editDistance(a, b, i + 1, j + 1);
return 1 + Math.min(insert, remove, replace);
}
editDistance('cat', 'cut', 0, 0);Done
The first 10 calls, of 14. This one does not fit on a page.
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.
- House robber Rob a house and skip its neighbour, or skip to the next.