Edit distance (Levenshtein)
A table where dp[i][j] is the cost of turning the first i characters of one string into the first j of the other. Each cell is either the diagonal unchanged (characters match) or one more than the cheapest of its three neighbours. O(m·n) time and space, reducible to O(min(m, n)).
Overview
What each neighbour means
The three options are not arbitrary; each is one edit:
Diagonal (dp[i-1][j-1]) — substitute one character for the other. Free when they already match.
Up (dp[i-1][j]) — delete a character from the first string.
Left (dp[i][j-1]) — insert a character into the first string.
Being able to say which is which is what separates understanding the recurrence from having memorised it.
Step through it
What to watch
- The edges are free to fill: i deletions to reach the empty string.
- A match copies the diagonal — no cost added at all.
- Each neighbour corresponds to one specific edit.
Say this out loud
"Classic DP. dp[i][j] is the cost for the two prefixes. If the characters match it's the diagonal; otherwise it's 1 plus the min of diagonal, left and up - substitute, insert, delete. O(m·n), and you only need two rows so space can be O(min(m,n))."