Edit Distance
Minimum insert / delete / replace operations to turn word1 into word2.
Intuition
Same skeleton as LCS: compare prefix pairs. dp[i][j] = cost to convert word1[:i] into word2[:j]. Matching last characters cost nothing — inherit the diagonal. Otherwise the last edit must be one of exactly three moves (replace, delete, insert), each reducing to a neighboring smaller subproblem — take the cheapest and add 1.
Approach
Base cases are the frame
dp[i][0] = i (delete everything), dp[0][j] = j (insert everything).
Three moves, three neighbors
Mismatch at (i,j): replace → dp[i-1][j-1]+1, delete word1's char → dp[i-1][j]+1, insert word2's char → dp[i][j-1]+1. Match: dp[i-1][j-1] free.
Why this is complete
Any optimal edit script has some last operation touching the ends, and it must be one of these three (or a free match) — so the min over them is optimal. Classic Levenshtein distance.
Solution & live demo
Edge cases
Answer is the other word's length (all inserts or all deletes).
Diagonal is free all the way — 0.
max(m,n): replace along the diagonal, insert/delete the remainder.