algosdynamic programming
dynamic programming
solve each small problem once, keep the answers in a table, and build the big answer from them.
a problem whose answer comes from the answers to smaller copies of itself, where the same copies come up again and again. answer each one once, keep it in a table, and look it up after that.
- time
- O(m × n) a cell for each pair of prefixes, each filled once from three others
- space
- O(m × n) the table, or two rows when only the distance is needed
- plain recursion
- exponential 5 stairs take 15 calls, 30 take 2,692,537
- needs
- overlap the same subproblems come back, and the best answer is built from best answers
- how many ways, the fewest steps, the most value, over a chain of choices
- edit distance, diff, spell checking, sequence alignment
- knapsack, coin change, cutting and scheduling problems
- shortest paths with negative edges, and parsing
- any recursion that calls itself on the same inputs again
on this page
dynamic programming is a way to run a recursion without repeating yourself. some problems break into smaller copies of themselves, and the same small copies come up over and over. answer each copy once, keep the answer in a table, and build the big answer from the table. the name is richard bellman’s, from the 1950s.1 climbing stairs shows the idea in one dimension. edit distance, the fewest edits that turn one word into another, is the main example: a table in two dimensions, and a walk back through it that reads the edits off.
the idea
an animation in six steps. first the question: how many ways up 5 stairs, taking 1 or 2 at a time, drawn as a box labeled 5 for ways(5) over boxes for the two calls it makes, ways(4) and ways(3). every box is labeled with the stairs its call asks about. then the call tree of the plain recursion grows one call at a time, in the order the calls happen: 15 calls in 5 levels, with 8 leaves. the 9 calls whose answer was already worked out earlier turn amber, and they make up whole subtrees: ways(3) under ways(5) repeats everything ways(3) did under ways(4). then the memo: the 3 repeats whose caller isn't a repeat are marked memo and answered at once, and the 6 calls under them fade out, leaving 9 calls. then a row of 6 cells, 0 to 5, fills left to right: 1, 1, 2, 3, 5, 8, each cell the sum of the two before it, with the two it reads in cyan and the cell being filled in white. as each cell fills, the memo's call that works out the same answer turns white in the tree, so the light climbs from ways(0) at the bottom to ways(5) at the top. last, 8 shows under ways(5), and the counts read 15 calls, 9 repeats, 9 calls with the memo and 6 cells.
two things made this work. the problem splits into smaller copies of itself, and the copies overlap: the same ones come back. merge sort splits a problem too, but its two halves are never the same problem twice, so there’s nothing to look up, and a table would hold answers nobody asks for again. the three climbs, as code:
ways(n): # how many ways up n stairs, 1 or 2 at a time. plain recursion
if n <= 1: return 1
return ways(n - 1) + ways(n - 2) # the same calls, over and over
ways_memo(n, memo): # top down: each answer is kept the first time
if n <= 1: return 1
if n in memo: return memo[n] # seen before: answered at once
memo[n] = ways_memo(n - 1, memo) + ways_memo(n - 2, memo)
return memo[n]
ways_table(n): # bottom up: every answer once, in order
t = [1, 1] + [0] * (n - 1) # t[k]: the ways up k stairs
for k in range(2, n + 1):
t[k] = t[k - 1] + t[k - 2] # the two cells before it
return t[n]watch it run
edit distance is the same idea in two dimensions: the fewest single-letter edits, insert, delete or replace, that turn kitten into sitting.2 the small copies are prefixes. the cell at row i, column j holds the fewest edits from the first i letters of kitten to the first j letters of sitting, and it comes from the three cells above and left of it: above is a delete, the left an insert, up and left a keep when the two letters match or a replace when they don’t. step through the table filling up. the cell being filled is white, the cells above and to the left are cyan, and the cell up and left is amber, with the two letters compared in amber too, since they decide what it costs. the pseudocode follows along.
white: being filled. cyan: + 1. amber: + 0 if the amber letters match, else + 1
a table of 7 rows and 8 columns: a row for each prefix of kitten and a column for each prefix of sitting, the empty prefix first
- cells filled
- 0 of 56
- matches
- 0
- step
- 1 of 46
edit_table(a, b): # a and b as utf-8 bytes m, n = len(a), len(b) t = (m + 1) rows of (n + 1) zeros # t[i][j]: a's first i bytes to b's first j for j in range(n + 1): t[0][j] = j # nothing to b's first j: j inserts for i in range(m + 1): t[i][0] = i # a's first i to nothing: i deletes for i in range(1, m + 1): for j in range(1, n + 1): same = 0 if a[i - 1] == b[j - 1] else 1 t[i][j] = min(t[i - 1][j] + 1, # above: delete a[i - 1] t[i][j - 1] + 1, # left: insert b[j - 1] t[i - 1][j - 1] + same) # up and left: keep, or replace return t # every pair of prefixes, answered once edit_distance(a, b): t = edit_table(a, b) return t[len(a)][len(b)] # the bottom right cell edit_script(a, b): # = keep, r replace, d delete, i insert t = edit_table(a, b) i, j = len(a), len(b) # walk back from the bottom right steps = [] while i > 0 or j > 0: if i > 0 and j > 0 and a[i - 1] == b[j - 1] and t[i][j] == t[i - 1][j - 1]: steps.append('='); i, j = i - 1, j - 1 # the bytes match: keep elif i > 0 and j > 0 and t[i][j] == t[i - 1][j - 1] + 1: steps.append('r'); i, j = i - 1, j - 1 # one more than up and left: replace elif i > 0 and t[i][j] == t[i - 1][j] + 1: steps.append('d'); i -= 1 # one more than above: delete else: steps.append('i'); j -= 1 # one more than the left: insert return reversed(steps)an interactive stepper over the edit-distance table for kitten against sitting: 7 rows of 8 cells, with the letters of kitten down the side and the letters of sitting along the top, and an empty prefix first on each side. the first step fills row 0 with 0 to 7 and the next fills column 0 with 0 to 6. then each step fills one cell, left to right and row by row, in white, with the cell above and the cell to the left in cyan, the cell up and left in amber, and the two letters compared in amber in the headers. a note says what the cell read: for e against i, above 2 + 1, left 2 + 1 and up and left 1 + 1, so 2, a replace; for t against t, a match, so the 1 up and left carries over. the matching pseudocode line is highlighted, with counts of the cells filled and the matches so far. after 56 cells the bottom right reads 3. a menu picks flaw and lawn, or café and cafe, where é is the two bytes c3 and a9, instead, and a button makes two random words of 3 to 7 letters from a to d.
the table is 56 cells, each filled once. the 42 past row 0 and column 0 each read three neighbors and compare two letters, and 7 of those compares match. the bottom right cell is the answer, 3, and it never had to know which three edits: that’s the walk back, further down. then pick flaw and lawn. letter by letter they differ in all four places, but the distance is 2, delete f and insert n, since the table is free to shift the letters along.2
try it
one cell at a time. the three neighbors are given: what goes in the cell, and which one did it come from?
e against i: above is 2, left is 2, up and left is 1. what goes in the cell?
pick one.
a practice exercise on small edit-distance tables. some questions show a table filled up to one cell, the cell blank and white, the cells above and to the left in cyan, the cell up and left in amber, and the two letters compared, and ask what goes in it, with the traps as choices: charging for a match, or not charging for a mismatch. others show a filled cell and ask which neighbor it came from, answered by tapping the neighbor; only cells with one way in are asked. the rest ask how many edits turn one short word into another, showing the table's first row and column and then the whole table once answered, or how many cells the table for two words has, where forgetting the empty prefix is the trap.
pseudocode
edit_table(a, b): # a and b as utf-8 bytes
m, n = len(a), len(b)
t = (m + 1) rows of (n + 1) zeros # t[i][j]: a's first i bytes to b's first j
for j in range(n + 1): t[0][j] = j # nothing to b's first j: j inserts
for i in range(m + 1): t[i][0] = i # a's first i to nothing: i deletes
for i in range(1, m + 1):
for j in range(1, n + 1):
same = 0 if a[i - 1] == b[j - 1] else 1
t[i][j] = min(t[i - 1][j] + 1, # above: delete a[i - 1]
t[i][j - 1] + 1, # left: insert b[j - 1]
t[i - 1][j - 1] + same) # up and left: keep, or replace
return t # every pair of prefixes, answered once
edit_distance(a, b):
t = edit_table(a, b)
return t[len(a)][len(b)] # the bottom right cell
edit_script(a, b): # = keep, r replace, d delete, i insert
t = edit_table(a, b)
i, j = len(a), len(b) # walk back from the bottom right
steps = []
while i > 0 or j > 0:
if i > 0 and j > 0 and a[i - 1] == b[j - 1] and t[i][j] == t[i - 1][j - 1]:
steps.append('='); i, j = i - 1, j - 1 # the bytes match: keep
elif i > 0 and j > 0 and t[i][j] == t[i - 1][j - 1] + 1:
steps.append('r'); i, j = i - 1, j - 1 # one more than up and left: replace
elif i > 0 and t[i][j] == t[i - 1][j] + 1:
steps.append('d'); i -= 1 # one more than above: delete
else:
steps.append('i'); j -= 1 # one more than the left: insert
return reversed(steps)the table has a row and a column more than the words have letters: row 0 and column 0 are the empty prefix, and the base cases. t[i][j] reads three cells that are all filled already, since the rows fill top to bottom, each one left to right. the walk back checks the four ways in a fixed order, keep, replace, delete, insert, so every tab returns the same script when several are shortest. everything is over the strings’ utf-8 bytes, so every tab agrees on any string.
the walk back, up close
white: where the walk is. ringed: the cells it came through
start at the bottom right, 3: the distance. which neighbor did it come from?
- script
- empty
- edits
- 0
the finished kitten against sitting table, 7 rows of 8, with a slider that walks back from the bottom right cell, 3, to the top left, one cell a step. the cell the walk is at is white, the cells it came through are ringed, and the letters of the step just taken light up in the headers: amber for a keep or a replace, cyan for a delete or an insert. a note says which neighbor the cell came from. the bottom right, 3, is one more than the 2 to its left: insert g. then n and n match and the 2 up and left is the same: keep n. then 2 is one more than the 1 up and left, and e and i differ: replace e with i. then t, t and i: three keeps down the diagonal. last, 1 is one more than the 0 up and left: replace k with s. under the table, kitten and sitting line up a column at a time as the script builds up on the front, i, =i, r=i, up to r===r=i, which is 3 edits, with a gap over the g.
- the table remembers how, not just how many. a cell’s value came from one of three neighbors, and the neighbor says which edit: above is a delete, the left an insert, up and left a keep or a replace. walking back from the bottom right along those neighbors lists the edits, last one first
- which neighbor, when several fit. two or three neighbors can give the same value: a tie between two shortest scripts. the walk takes keep first, then replace, then delete, then insert, and every tab does the same, so kitten to sitting is always r===r=i: replace k, keep i, t and t, replace e, keep n, insert g
- the count. each step moves up, left or both, so the walk takes at most m + n steps, 13 here, and kitten and sitting take 7. the letters other than = count the distance, 3
- the cost of knowing. the walk needs the whole table. when only the distance is needed, each row reads only itself and the row above, so two rows are enough: 2,002 numbers for two words of 1,000 letters, instead of 1,002,001. hirschberg showed in 1975 how to get the answer itself, for the longest common subsequence, in linear space too3
complexity
| plain recursion | memo | table | |
|---|---|---|---|
| climbing n stairs | 2 × ways(n) - 1 calls | 2n - 1 calls | n + 1 cells |
| edit distance, m by n | exponential | up to (m + 1)(n + 1) answers | (m + 1)(n + 1) cells |
| space | the call stack | the memo and the stack | the table, or two rows |
climbing stairs by plain recursion makes about two calls per way up, 2 × ways(n) - 1 of them, and the ways grow by about 1.6 each stair: they’re the fibonacci numbers. the memo works out each ways(k) from 2 up to n once, with two calls each, and with the first call that’s 2n - 1. the table is n + 1 cells and no calls at all. for edit distance the same move turns an exponential recursion into (m + 1)(n + 1) cells, each filled in O(1) from three neighbors: O(m × n) time and space, and O(n) space with two rows.
- table
- 65 steps
- memo
- 127 steps
- plain recursion
- 34,335,360,355,129 steps
a line chart of steps against stairs, from 1 to 64 on a doubling scale, with the top at 150 and a slider that picks a size and reads off every line. a step is a call for the plain recursion and the memo, and a cell for the table. the table, solid cyan, is n + 1 cells: 2 at 1 and 65 at 64. the memo, dashed cyan, is 2n - 1 calls: 1 at 1 and 127 at 64. the plain recursion, amber, is 1, 3, 9 and 67 calls at 1, 2, 4 and 8, then leaves the top between 8 and 16: 3,193 calls at 16, 7,049,155 at 32 and 34,335,360,355,129 at 64.
on the chart the plain recursion is off the top before 16 stairs: 3,193 calls there, 7,049,155 at 32, and 34,335,360,355,129 at 64, where the memo makes 127 calls and the table has 65 cells. the two cheap lines look like they curve up only because the stairs double along the axis: both are straight lines in n.
implementations
each tab is the real file from the repo, checked by its tests (go test, cargo test, vitest, make test, swift test, python -m unittest), including 2000 seeded pairs of short words against a memoized top-down recursion, the script of each pair run to turn the first word into the second, and two words of 1,000 letters, a table of 1,002,001 cells. every tab works over the strings’ utf-8 bytes, so they agree on any string: café to cafe is 2, since é is two bytes. every tab walks back in the same order, keep, replace, delete, insert, so the scripts match too: kitten to sitting is r===r=i in all six. c keeps the table in one block, row after row, and writes the script into a buffer of m + n + 1 bytes that the caller hands it; it answers -1 or false only when the table can’t be allocated.
// Package editdistance is a reference edit distance, as dynamic programming: the fewest single-byte edits
// (insert, delete, replace) that turn one string into another. the answer for two whole strings is built
// from the answers for their prefixes, each one worked out once and kept in a table. over utf-8 bytes, so
// every language agrees on any string: a letter outside ascii counts as the 2 to 4 bytes it takes.
package editdistance
import "slices"
// Table returns the table: t[i][j] is the fewest edits from a's first i bytes to b's first j bytes, so
// (m + 1) rows of (n + 1). Row 0 and column 0 are the empty prefix: j inserts, or i deletes. Every other
// cell is the smallest of the cell above + 1 (delete a's byte), the cell to the left + 1 (insert b's
// byte), and the cell up and left + 0 when the two bytes match or + 1 when they don't (keep, or replace).
// The answer is the bottom right cell. a[i] is a byte, where range a would step a whole rune at a time.
func Table(a, b string) [][]int {
m, n := len(a), len(b)
t := make([][]int, m+1)
for i := range t {
t[i] = make([]int, n+1)
}
for j := range n + 1 {
t[0][j] = j // nothing to b's first j bytes: j inserts
}
for i := range m + 1 {
t[i][0] = i // a's first i bytes to nothing: i deletes
}
for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
cost := 1 // the bytes differ: replace
if a[i-1] == b[j-1] {
cost = 0 // they match: keep
}
t[i][j] = min(t[i-1][j]+1, t[i][j-1]+1, t[i-1][j-1]+cost)
}
}
return t
}
// Distance returns the fewest edits from a to b: the table's bottom right cell.
func Distance(a, b string) int {
return Table(a, b)[len(a)][len(b)]
}
// Script returns one way to make the edits, one letter per step: = keep, r replace, d delete, i insert. It
// walks the table back from the bottom right corner. At each cell it asks which neighbor the cell came
// from, in this order: keep when the two bytes match and the cell up and left equals this one, else
// replace when the cell up and left is one less, else delete when the cell above is one less, else insert.
// The path, reversed, is the script, and its letters other than = count the distance.
func Script(a, b string) string {
t := Table(a, b)
var steps []byte
i, j := len(a), len(b)
for i > 0 || j > 0 {
switch {
case i > 0 && j > 0 && a[i-1] == b[j-1] && t[i][j] == t[i-1][j-1]:
steps = append(steps, '=') // the bytes match: keep a's, at the cost of the cell up and left
i, j = i-1, j-1
case i > 0 && j > 0 && t[i][j] == t[i-1][j-1]+1:
steps = append(steps, 'r') // replace a's byte with b's
i, j = i-1, j-1
case i > 0 && t[i][j] == t[i-1][j]+1:
steps = append(steps, 'd') // delete a's byte
i--
default:
steps = append(steps, 'i') // insert b's byte
j--
}
}
slices.Reverse(steps)
return string(steps)
}//! edit distance, as dynamic programming: the fewest single-byte edits (insert, delete, replace) that turn one string into another. the answer for two whole strings is built from the answers for their prefixes, each one worked out once and kept in a table. over utf-8 bytes, so every language agrees on any string: a letter outside ascii counts as the 2 to 4 bytes it takes.
/// The table: `t[i][j]` is the fewest edits from `a`'s first i bytes to `b`'s first j bytes, so
/// (m + 1) rows of (n + 1). Row 0 and column 0 are the empty prefix: j inserts, or i deletes.
/// Every other cell is the smallest of the cell above + 1 (delete `a`'s byte), the cell to the
/// left + 1 (insert `b`'s byte), and the cell up and left + 0 when the two bytes match or + 1 when
/// they don't (keep, or replace). The answer is the bottom right cell.
pub fn edit_table(a: &str, b: &str) -> Vec<Vec<usize>> {
let (x, y) = (a.as_bytes(), b.as_bytes());
let (m, n) = (x.len(), y.len());
let mut t = vec![vec![0; n + 1]; m + 1];
for (j, cell) in t[0].iter_mut().enumerate() {
*cell = j; // nothing to b's first j bytes: j inserts
}
for (i, row) in t.iter_mut().enumerate() {
row[0] = i; // a's first i bytes to nothing: i deletes
}
for i in 1..=m {
for j in 1..=n {
let same = if x[i - 1] == y[j - 1] { 0 } else { 1 };
t[i][j] = (t[i - 1][j] + 1)
.min(t[i][j - 1] + 1)
.min(t[i - 1][j - 1] + same);
}
}
t
}
/// The fewest edits from `a` to `b`: the table's bottom right cell.
pub fn edit_distance(a: &str, b: &str) -> usize {
let t = edit_table(a, b);
t[a.len()][b.len()]
}
/// One way to make the edits, one letter per step: `=` keep, `r` replace, `d` delete, `i` insert.
/// It walks the table back from the bottom right corner. At each cell it asks which neighbor the
/// cell came from, in this order: keep when the two bytes match and the cell up and left equals
/// this one, else replace when the cell up and left is one less, else delete when the cell above
/// is one less, else insert. The path, reversed, is the script, and its letters other than `=`
/// count the distance.
pub fn edit_script(a: &str, b: &str) -> String {
let (x, y) = (a.as_bytes(), b.as_bytes());
let t = edit_table(a, b);
let mut steps = Vec::new();
let (mut i, mut j) = (x.len(), y.len());
while i > 0 || j > 0 {
if i > 0 && j > 0 && x[i - 1] == y[j - 1] && t[i][j] == t[i - 1][j - 1] {
// the bytes match: keep a's, and the cost came from the cell up and left
steps.push('=');
i -= 1;
j -= 1;
} else if i > 0 && j > 0 && t[i][j] == t[i - 1][j - 1] + 1 {
steps.push('r'); // replace a's byte with b's
i -= 1;
j -= 1;
} else if i > 0 && t[i][j] == t[i - 1][j] + 1 {
steps.push('d'); // delete a's byte
i -= 1;
} else {
steps.push('i'); // insert b's byte
j -= 1;
}
}
steps.iter().rev().collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
/// xorshift32 seeded with `seed`, like the other tests here: each call gives the next number.
fn xorshift32(seed: u32) -> impl FnMut() -> usize {
let mut state = seed;
move || {
state ^= state << 13;
state ^= state >> 17;
state ^= state << 5;
state as usize
}
}
/// The memo: the distance from `a`'s first i bytes to `b`'s first j, kept by (i, j).
type Memo = HashMap<(usize, usize), usize>;
/// The distance by top-down recursion with a memo, over the strings' bytes: the brute force.
fn memo_distance(a: &str, b: &str) -> usize {
fn go(x: &[u8], y: &[u8], i: usize, j: usize, memo: &mut Memo) -> usize {
if i == 0 {
return j;
}
if j == 0 {
return i;
}
if let Some(&d) = memo.get(&(i, j)) {
return d;
}
let d = if x[i - 1] == y[j - 1] {
go(x, y, i - 1, j - 1, memo)
} else {
1 + go(x, y, i - 1, j, memo)
.min(go(x, y, i, j - 1, memo))
.min(go(x, y, i - 1, j - 1, memo))
};
memo.insert((i, j), d);
d
}
let (x, y) = (a.as_bytes(), b.as_bytes());
go(x, y, x.len(), y.len(), &mut Memo::new())
}
/// Runs a script on `a`, byte by byte, and returns what comes out: `b`, when the script is
/// right. `=` copies `a`'s next byte, which has to be `b`'s next byte too, `r` and `i` take
/// `b`'s next byte, and `d` skips `a`'s.
fn apply(a: &str, b: &str, script: &str) -> Vec<u8> {
let (x, y) = (a.as_bytes(), b.as_bytes());
let (mut i, mut j) = (0, 0);
let mut out = Vec::new();
for step in script.chars() {
match step {
'=' => {
assert_eq!(x[i], y[j]);
out.push(x[i]);
i += 1;
j += 1;
}
'r' => {
out.push(y[j]);
i += 1;
j += 1;
}
'd' => i += 1,
'i' => {
out.push(y[j]);
j += 1;
}
_ => panic!("no such step: {step}"),
}
}
assert_eq!((i, j), (x.len(), y.len())); // the script used up both strings
out
}
/// The edits in a script: every letter but `=`.
fn edits(script: &str) -> usize {
script.chars().filter(|&c| c != '=').count()
}
/// 2000 seeded pairs, each word 0 to 8 letters over a, b and c, so matches and ties are common.
fn pairs() -> Vec<(String, String)> {
let mut next = xorshift32(42);
let mut word = move || -> String {
(0..next() % 9)
.map(|_| ['a', 'b', 'c'][next() % 3])
.collect()
};
(0..2000).map(|_| (word(), word())).collect()
}
#[test]
fn nothing_to_nothing_is_0_nothing_to_abc_is_3_inserts_abc_to_nothing_3_deletes_and_abc_to_abc_keeps_all_three()
{
assert_eq!((edit_distance("", ""), edit_script("", "")), (0, "".into()));
assert_eq!(
(edit_distance("", "abc"), edit_script("", "abc")),
(3, "iii".into())
);
assert_eq!(
(edit_distance("abc", ""), edit_script("abc", "")),
(3, "ddd".into())
);
assert_eq!(
(edit_distance("abc", "abc"), edit_script("abc", "abc")),
(0, "===".into())
);
}
#[test]
fn kitten_to_sitting_is_3_replace_k_keep_itt_replace_e_keep_n_insert_g() {
assert_eq!(edit_distance("kitten", "sitting"), 3);
assert_eq!(edit_script("kitten", "sitting"), "r===r=i");
}
#[test]
fn flaw_to_lawn_is_2_and_intention_to_execution_is_5_with_their_scripts() {
assert_eq!(
(edit_distance("flaw", "lawn"), edit_script("flaw", "lawn")),
(2, "d===i".into())
);
assert_eq!(
(
edit_distance("intention", "execution"),
edit_script("intention", "execution")
),
(5, "rrrrr====".into())
);
}
#[test]
fn the_kitten_to_sitting_table_7_rows_of_8_the_first_row_0_to_7_the_first_column_0_to_6_and_the_last_row_6_6_5_4_3_3_2_3()
{
let t = edit_table("kitten", "sitting");
assert_eq!((t.len(), t[0].len()), (7, 8));
assert_eq!(t[0], [0, 1, 2, 3, 4, 5, 6, 7]);
assert_eq!(
t.iter().map(|row| row[0]).collect::<Vec<_>>(),
[0, 1, 2, 3, 4, 5, 6]
);
assert_eq!(t[6], [6, 6, 5, 4, 3, 3, 2, 3]);
}
#[test]
fn bytes_café_to_cafe_is_2_since_é_is_two_bytes() {
assert_eq!(edit_distance("café", "cafe"), 2);
// 5 bytes against 4: 6 rows of 5. the script keeps c, a and f, drops one byte of é and
// replaces the other
let t = edit_table("café", "cafe");
assert_eq!(
(t.len(), t[0].len(), edit_script("café", "cafe")),
(6, 5, "===dr".into())
);
}
#[test]
fn agrees_with_a_memoized_recursion_on_2000_seeded_pairs() {
for (a, b) in pairs() {
assert_eq!(edit_distance(&a, &b), memo_distance(&a, &b), "{a} to {b}");
}
}
#[test]
fn on_the_same_pairs_the_script_turns_a_into_b_and_its_letters_other_than_keep_count_the_distance()
{
for (a, b) in pairs() {
let script = edit_script(&a, &b);
assert_eq!(apply(&a, &b, &script), b.as_bytes());
assert_eq!(edits(&script), edit_distance(&a, &b));
}
}
#[test]
fn symmetric_and_between_the_difference_of_the_lengths_and_the_longer_length() {
for (a, b) in pairs() {
let d = edit_distance(&a, &b);
assert_eq!(edit_distance(&b, &a), d);
assert!(d >= a.len().abs_diff(b.len()));
assert!(d <= a.len().max(b.len()));
}
}
#[test]
fn two_words_of_1000_letters_a_table_of_1001_by_1001_cells_filled_in_one_go() {
let mut next = xorshift32(7);
let mut word = || -> String {
(0..1000)
.map(|_| ['a', 'b', 'c', 'd'][next() % 4])
.collect()
};
let a = word();
let b = word();
let t = edit_table(&a, &b);
assert_eq!(
(t.len(), t[0].len(), t.len() * t[0].len()),
(1001, 1001, 1_002_001)
);
let script = edit_script(&a, &b);
assert_eq!(apply(&a, &b, &script), b.as_bytes());
assert_eq!(edits(&script), t[1000][1000]);
}
}/**
* Edit distance, as dynamic programming: the fewest single-byte edits (insert, delete, replace) that turn one
* string into another. The answer for two whole strings is built from the answers for their prefixes, each one
* worked out once and kept in a table. Over utf-8 bytes, so every language agrees on any string: a letter outside
* ascii counts as the 2 to 4 bytes it takes.
*/
const utf8 = (s: string) => new TextEncoder().encode(s);
/**
* The table: t[i][j] is the fewest edits from a's first i bytes to b's first j bytes, so (m + 1) rows of (n + 1).
* Row 0 and column 0 are the empty prefix: j inserts, or i deletes. Every other cell is the smallest of the cell
* above + 1 (delete a's byte), the cell to the left + 1 (insert b's byte), and the cell up and left + 0 when the
* two bytes match or + 1 when they don't (keep, or replace). The answer is the bottom right cell.
*/
export function editTable(a: string, b: string): number[][] {
const x = utf8(a);
const y = utf8(b);
const m = x.length;
const n = y.length;
const t: number[][] = Array.from({ length: m + 1 }, () => Array<number>(n + 1).fill(0));
for (let j = 0; j <= n; j++) t[0][j] = j; // nothing to b's first j bytes: j inserts
for (let i = 0; i <= m; i++) t[i][0] = i; // a's first i bytes to nothing: i deletes
for (let i = 1; i <= m; i++)
for (let j = 1; j <= n; j++) {
const same = x[i - 1] === y[j - 1] ? 0 : 1;
t[i][j] = Math.min(t[i - 1][j] + 1, t[i][j - 1] + 1, t[i - 1][j - 1] + same);
}
return t;
}
/** The fewest edits from a to b: the table's bottom right cell. */
export function editDistance(a: string, b: string): number {
const t = editTable(a, b);
return t[t.length - 1][t[0].length - 1];
}
/**
* One way to make the edits, one letter per step: `=` keep, `r` replace, `d` delete, `i` insert. It walks the
* table back from the bottom right corner. At each cell it asks which neighbor the cell came from, in this order:
* keep when the two bytes match and the cell up and left equals this one, else replace when the cell up and left
* is one less, else delete when the cell above is one less, else insert. The path, reversed, is the script, and
* its letters other than `=` count the distance.
*/
export function editScript(a: string, b: string): string {
const x = utf8(a);
const y = utf8(b);
const t = editTable(a, b);
const steps: string[] = [];
let i = x.length;
let j = y.length;
while (i > 0 || j > 0) {
if (i > 0 && j > 0 && x[i - 1] === y[j - 1] && t[i][j] === t[i - 1][j - 1]) {
steps.push('='); // the bytes match: keep a's, and the cost came from the cell up and left
i -= 1;
j -= 1;
} else if (i > 0 && j > 0 && t[i][j] === t[i - 1][j - 1] + 1) {
steps.push('r'); // replace a's byte with b's
i -= 1;
j -= 1;
} else if (i > 0 && t[i][j] === t[i - 1][j] + 1) {
steps.push('d'); // delete a's byte
i -= 1;
} else {
steps.push('i'); // insert b's byte
j -= 1;
}
}
return steps.reverse().join('');
}/* edit distance, as dynamic programming: the fewest single-byte edits (insert, delete, replace) that turn one string into another. the answer for two whole strings is built from the answers for their prefixes, each one worked out once and kept in a table. over bytes, so in utf-8 a letter outside ascii counts as the 2 to 4 bytes it takes, and every language agrees on any string. */
#include "edit_distance.h"
#include <stdlib.h>
#include <string.h>
static int min3(int x, int y, int z) {
int m = x < y ? x : y;
return m < z ? m : z;
}
/* row 0 and column 0 are the empty prefix: j inserts, or i deletes. every other cell is the smallest
of the cell above + 1 (delete a's byte), the cell to the left + 1 (insert b's byte), and the cell
up and left + 0 when the two bytes match or + 1 when they don't (keep, or replace). a cell reads
only cells above it and to its left, so filling row by row, left to right, finds them done. the
table has at least one cell, so the malloc is never one of 0 bytes */
int *edit_table(const char *a, const char *b, size_t *rows_out, size_t *cols_out) {
size_t m = strlen(a), n = strlen(b), cols = n + 1;
*rows_out = m + 1;
*cols_out = cols;
int *t = malloc((m + 1) * cols * sizeof *t);
if (!t) return NULL;
for (size_t j = 0; j <= n; j++) t[j] = (int)j; /* nothing to b's first j bytes: j inserts */
for (size_t i = 0; i <= m; i++) t[i * cols] = (int)i; /* a's first i bytes to nothing: i deletes */
for (size_t i = 1; i <= m; i++) {
for (size_t j = 1; j <= n; j++) {
int same = a[i - 1] == b[j - 1] ? 0 : 1;
int above = t[(i - 1) * cols + j], left = t[i * cols + j - 1], diagonal = t[(i - 1) * cols + j - 1];
t[i * cols + j] = min3(above + 1, left + 1, diagonal + same);
}
}
return t;
}
/* the bottom right cell is the table's last */
int edit_distance(const char *a, const char *b) {
size_t rows, cols;
int *t = edit_table(a, b, &rows, &cols);
if (!t) return -1;
int d = t[rows * cols - 1];
free(t);
return d;
}
/* walks the table back from the bottom right corner. at each cell it asks which neighbor the cell
came from, in this order: keep when the two bytes match and the cell up and left equals this one,
else replace when the cell up and left is one less, else delete when the cell above is one less,
else insert. every step uses up a byte of a, of b, or of both, so the walk ends at the top left
corner within m + n steps. the steps come out last first, so out is reversed at the end */
bool edit_script(const char *a, const char *b, char *out) {
size_t rows, cols;
int *t = edit_table(a, b, &rows, &cols);
if (!t) return false;
/* the bottom right corner. a table always has a row and a column, so neither - 1 wraps */
size_t i = rows - 1, j = cols - 1, k = 0;
while (i > 0 || j > 0) {
int here = t[i * cols + j];
if (i > 0 && j > 0 && a[i - 1] == b[j - 1] && here == t[(i - 1) * cols + j - 1]) {
out[k++] = '='; /* the bytes match: keep a's, and the cost came from the cell up and left */
i--;
j--;
} else if (i > 0 && j > 0 && here == t[(i - 1) * cols + j - 1] + 1) {
out[k++] = 'r'; /* replace a's byte with b's */
i--;
j--;
} else if (i > 0 && here == t[(i - 1) * cols + j] + 1) {
out[k++] = 'd'; /* delete a's byte */
i--;
} else {
out[k++] = 'i'; /* insert b's byte. j is above 0 here: with j = 0, delete always fits */
j--;
}
}
free(t);
for (size_t lo = 0, hi = k; lo + 1 < hi; lo++) {
char c = out[lo];
out[lo] = out[--hi];
out[hi] = c;
}
out[k] = '\0';
return true;
}/// edit distance, as dynamic programming: the fewest single-byte edits (insert, delete, replace) that turn one string into another. the answer for two whole strings is built from the answers for their prefixes, each one worked out once and kept in a table. over utf-8 bytes, so every language agrees on any string: a letter outside ascii counts as the 2 to 4 bytes it takes.
/// the table: t[i][j] is the fewest edits from a's first i bytes to b's first j bytes, so (m + 1) rows of (n + 1).
/// row 0 and column 0 are the empty prefix: j inserts, or i deletes. every other cell is the smallest of the cell
/// above + 1 (delete a's byte), the cell to the left + 1 (insert b's byte), and the cell up and left + 0 when the
/// two bytes match or + 1 when they don't (keep, or replace). the answer is the bottom right cell
public func editTable(_ a: String, _ b: String) -> [[Int]] {
let x = Array(a.utf8)
let y = Array(b.utf8)
let m = x.count
let n = y.count
var t = [[Int]](repeating: [Int](repeating: 0, count: n + 1), count: m + 1)
for j in 0...n { t[0][j] = j } // nothing to b's first j bytes: j inserts
for i in 0...m { t[i][0] = i } // a's first i bytes to nothing: i deletes
// 1 up to m, and 1 up to n. 1...m would trap when a is empty
for i in 1..<m + 1 {
for j in 1..<n + 1 {
let same = x[i - 1] == y[j - 1] ? 0 : 1
t[i][j] = min(t[i - 1][j] + 1, t[i][j - 1] + 1, t[i - 1][j - 1] + same)
}
}
return t
}
/// the fewest edits from a to b: the table's bottom right cell
public func editDistance(_ a: String, _ b: String) -> Int {
editTable(a, b).last!.last!
}
/// one way to make the edits, one letter per step: = keep, r replace, d delete, i insert. it walks the table back
/// from the bottom right corner. at each cell it asks which neighbor the cell came from, in this order: keep when
/// the two bytes match and the cell up and left equals this one, else replace when the cell up and left is one
/// less, else delete when the cell above is one less, else insert. the path, reversed, is the script, and its
/// letters other than = count the distance
public func editScript(_ a: String, _ b: String) -> String {
let x = Array(a.utf8)
let y = Array(b.utf8)
let t = editTable(a, b)
var steps: [Character] = []
var i = x.count
var j = y.count
while i > 0 || j > 0 {
if i > 0 && j > 0 && x[i - 1] == y[j - 1] && t[i][j] == t[i - 1][j - 1] {
steps.append("=") // the bytes match: keep a's, and the cost came from the cell up and left
i -= 1
j -= 1
} else if i > 0 && j > 0 && t[i][j] == t[i - 1][j - 1] + 1 {
steps.append("r") // replace a's byte with b's
i -= 1
j -= 1
} else if i > 0 && t[i][j] == t[i - 1][j] + 1 {
steps.append("d") // delete a's byte
i -= 1
} else {
steps.append("i") // insert b's byte
j -= 1
}
}
return String(steps.reversed())
}"""edit distance, as dynamic programming: the fewest single-byte edits (insert, delete, replace) that turn one string into another. the answer for two whole strings is built from the answers for their prefixes, each one worked out once and kept in a table. over utf-8 bytes, so every language agrees on any string: a letter outside ascii counts as the 2 to 4 bytes it takes."""
from __future__ import annotations
def edit_table(a: str, b: str) -> list[list[int]]:
"""Return the table: t[i][j] is the fewest edits from a's first i bytes to b's first j bytes.
So (m + 1) rows of (n + 1). Row 0 and column 0 are the empty prefix: j inserts, or i deletes. Every other
cell is the smallest of the cell above + 1 (delete a's byte), the cell to the left + 1 (insert b's byte),
and the cell up and left + 0 when the two bytes match or + 1 when they don't (keep, or replace). The
answer is the bottom right cell.
"""
x = a.encode() # the utf-8 bytes
y = b.encode()
m = len(x)
n = len(y)
t = [[0] * (n + 1) for _ in range(m + 1)] # [[0] * (n + 1)] * (m + 1) would share one row
for j in range(n + 1):
t[0][j] = j # nothing to b's first j bytes: j inserts
for i in range(m + 1):
t[i][0] = i # a's first i bytes to nothing: i deletes
for i in range(1, m + 1):
for j in range(1, n + 1):
same = 0 if x[i - 1] == y[j - 1] else 1
t[i][j] = min(t[i - 1][j] + 1, t[i][j - 1] + 1, t[i - 1][j - 1] + same)
return t
def edit_distance(a: str, b: str) -> int:
"""Return the fewest edits from a to b: the table's bottom right cell."""
return edit_table(a, b)[-1][-1]
def edit_script(a: str, b: str) -> str:
"""Return one way to make the edits, one letter per step: = keep, r replace, d delete, i insert.
It walks the table back from the bottom right corner. At each cell it asks which neighbor the cell came
from, in this order: keep when the two bytes match and the cell up and left equals this one, else replace
when the cell up and left is one less, else delete when the cell above is one less, else insert. The path,
reversed, is the script, and its letters other than = count the distance.
"""
x = a.encode()
y = b.encode()
t = edit_table(a, b)
steps: list[str] = []
i = len(x)
j = len(y)
while i > 0 or j > 0:
if i > 0 and j > 0 and x[i - 1] == y[j - 1] and t[i][j] == t[i - 1][j - 1]:
steps.append("=") # the bytes match: keep a's, and the cost came from the cell up and left
i -= 1
j -= 1
elif i > 0 and j > 0 and t[i][j] == t[i - 1][j - 1] + 1:
steps.append("r") # replace a's byte with b's
i -= 1
j -= 1
elif i > 0 and t[i][j] == t[i - 1][j] + 1:
steps.append("d") # delete a's byte
i -= 1
else:
steps.append("i") # insert b's byte
j -= 1
steps.reverse()
return "".join(steps)pitfalls
- a table one short. the table has a row and a column for the empty prefix, so it’s (m + 1) by (n + 1), and
t[i][j]is about the first i letters, which end ata[i - 1]. size it m by n, or comparea[i], and a letter falls off one end. the size question in try it is this - reading a cell before it’s filled. bottom up, the order matters: a cell reads the cell above, the one to its left and the one up and left, so it has to come after all three. rows top to bottom, each left to right, does that, and so do columns left to right. start from the right and a cell reads a 0 that was never filled in. climbing stairs is the same in one dimension: ways(k) needs k - 1 and k - 2 done
- a memo key that misses part of the state. top down, the key has to be everything the answer depends on. keyed on i alone, edit distance hands back the answer for some other j, and nothing says it went wrong
- recursion depth. top down nests as deep as the longest chain of subproblems, up to m + n calls for edit distance, and a long enough input hits the stack limit. bottom up never nests
- charging for a match. when the letters match, the cell up and left carries over with nothing added. adding 1 anyway counts a replace that isn’t needed. it’s one of the traps in try it
- stopping at the distance. the bottom right cell says how many edits, not which. the walk back is the second half of the algorithm, and it needs the whole table, so the two-row trick gives it up
variants
- longest common subsequence. the same table with other costs: a match adds 1 to the cell up and left, otherwise take the bigger of above and left. diff tools are built on it, and the walk back lists the lines kept
- coin change and knapsack. one dimension per thing that can vary: the amount left, the items considered, the room left. the fewest coins for an amount is 1 plus the fewest for the amount minus a coin, over the coins; 0/1 knapsack is a table of items by capacity
- two rows. when a row only reads the row above it, keep two and swap them: edit distance’s distance, the length of a longest common subsequence, knapsack’s best value. the script or the chosen items need the whole table, or hirschberg’s trick3
- other costs. levenshtein’s 1965 paper counted deletions, insertions and reversals in binary words, for error-correcting codes, and it has no table in it. jurafsky and martin say wagner and fischer named the table algorithm in 1974, and that many people found it on their own.4,5,6 the costs are a choice: their intention to execution is 5 with a replace at 1, and 8 with a replace at 2, where a replace costs as much as a delete and an insert.6 git weighs its edits differently again, below
- transpositions. damerau-levenshtein counts a swap of two neighboring letters as one edit, with a fourth neighbor two rows up and two cells left. rustc and git both use it for their suggestions, below
- a shortest path. every cell is a point, and every edit a step from a neighbor that costs 1, or 0 for a keep. the distance is the cheapest path from the top left corner to the bottom right. dijkstra’s algorithm would find it with a heap, but the table doesn’t need one: every step goes down, right or both, so filling row by row reaches each cell after every cell that leads into it
- top down or bottom up. a memo visits only the subproblems the answer needs and keeps the recursion’s shape; the table visits all of them, in an order you pick, and never nests. when most of the table is needed the table wins; when little of it is, the memo does
practice
- climbing stairs (opens in a new tab): the movie’s problem
- edit distance (opens in a new tab): the stepper’s table, bottom right cell
- longest common subsequence (opens in a new tab): the same table, other costs
- coin change (opens in a new tab): the fewest coins, in one dimension
- house robber (opens in a new tab): each cell from the two before it, with a choice
- unique paths (opens in a new tab): a grid where each cell is the sum of above and left
how real libraries do it
the did-you-mean suggestions in three tools are edit distance, with a twist each:
- python. a
NameErrororAttributeErrorsuggests a close name:traceback.pygathers the names in reach and hands them to the c code insuggestions.c. it runs levenshtein over the names’ utf-8 bytes, where an insert, a delete or a replace costs 2 and a change of case 1, updates one row in place instead of keeping the whole table, and gives up on a candidate as soon as a whole row is over the cap. the cap lets no more than about a third of the characters change, a pair with more than 40 bytes left after the common ends are trimmed is skipped, and the closest candidate wins7 - rustc. an unknown name gets a hint about a similar one.
edit_distanceinrustc_spanis the restricted damerau-levenshtein distance, over chars, with a limit it checks early and the common prefix and suffix stripped first; it keeps three rows, since a transposition reads two rows up.find_best_match_for_nametries an exact case-insensitive match first, then the distance with a limit of a third of the name’s length, then the same words in another order8 - git.
git stautsprints the most similar command.levenshtein.cis damerau-levenshtein with a weight per kind of edit, kept in three rows, andhelp.ccalls it with swaps at 0, replacements at 2, inserts at 1 and deletes at 3, so a typo that drops a letter counts for less than one that adds one. the most similar commands are listed when the best score is under a floor of 7, and withhelp.autocorrectset and a single best match, git runs it9
sources
-
richard bellman, the theory of dynamic programming (opens in a new tab), bulletin of the american mathematical society 60(6), pages 503 to 515, 1954, and dynamic programming, princeton university press, 1957. the press’s page (opens in a new tab) for the 2010 reprint calls him the scientist who coined the term. ↩
-
levenshtein distance (opens in a new tab) on wikipedia: kitten to sitting is 3, substitute s for k, substitute i for e and insert g, and flaw to lawn is 2, delete f and insert n, where their hamming distance is 4. ↩ ↩2
-
d. s. hirschberg, a linear space algorithm for computing maximal common subsequences (opens in a new tab), communications of the acm 18(6), pages 341 to 343, june 1975. ↩ ↩2
-
v. i. levenshtein, binary codes capable of correcting deletions, insertions, and reversals, soviet physics doklady 10(8), pages 707 to 710, february 1966, translated from doklady akademii nauk sssr 163(4), pages 845 to 848, 1965. it defines the distance between two binary words as the smallest number of deletions and insertions, then with reversals too, that turn one into the other, shows it’s a metric, and uses it for codes. no algorithm for computing it is given. ↩
-
robert a. wagner and michael j. fischer, the string-to-string correction problem (opens in a new tab), journal of the acm 21(1), pages 168 to 173, january 1974. ↩
-
daniel jurafsky and james h. martin, speech and language processing (opens in a new tab), 3rd edition draft of august 19, 2026, chapter 2 (opens in a new tab), section 2.9: the minimum edit distance between intention and execution is 5 with every edit at 1, and 8 under levenshtein’s other version, where a substitution costs as much as a deletion plus an insertion; the algorithm was named by wagner and fischer in 1974 but discovered independently by many people; and, in the chapter’s historical notes, their example is adapted from kruskal, 1983. ↩ ↩2
-
cpython 3.15.0.
_compute_suggestion_error(opens in a new tab) inLib/traceback.pygathers the candidates for anAttributeError, aNameErroror anImportErrorand passes them (opens in a new tab) to the_suggestionsmodule (opens in a new tab), which calls_Py_CalculateSuggestions; a copy of the same search in python takes over when that module isn’t there. Python/suggestions.c (opens in a new tab): an insert or a delete costs 2 (MOVE_COST), a replace 2, and a change of case 1 (CASE_COST), and nothing is suggested from 750 candidates or more.levenshtein_distance(opens in a new tab) trims the common prefix and suffix, skips a pair with more than 40 bytes left on a side, updates one row in place instead of the whole matrix, and bails out when a whole row is over the cap._Py_CalculateSuggestions(opens in a new tab) compares the names as utf-8 bytes, caps the distance so that no more than a third of the characters involved need to change, and keeps the closest candidate._Py_UTF8_Edit_Cost(opens in a new tab) is the same distance over two strings’ utf-8 bytes. ↩ -
edit_distance.rs (opens in a new tab) in rustc 1.99.1: the implementation is the restricted damerau-levenshtein algorithm.
edit_distance(opens in a new tab) works over chars, gives none past a limit, returns early when the difference in length alone passes it, strips the common prefix and suffix, keeps three rows, and counts a transposition as one.find_best_match_for_name(opens in a new tab) takes an optional limit that defaults to a third of the word, and tries an exact case-insensitive match, then the edit distance, then a match of the same words sorted. ↩ -
git 2.56.0. levenshtein.c (opens in a new tab): damerau-levenshtein with a weight each for a swap, a substitution, an insertion and a deletion, keeping only the last three rows. help.c (opens in a new tab) sets the similarity floor at 7, scores each command (opens in a new tab) at its distance plus one, with swaps at 0, substitutions at 2, insertions at 1 and deletions at 3, and a common command that starts with what was typed at 0, and lists the most similar commands (opens in a new tab) when the best score is under the floor, or runs the single best one when
help.autocorrectsays so. ↩