Edit distance
Edit distance, or Levenshtein distance, is the fewest changes needed to turn one text into another. There are 3 possible changes: insert a letter, delete a letter or replace a letter with another. From «kitten» to «sitting» there are 3: 2 replacements and 1 insertion. It is used in search engines and language processing to measure how similar 2 texts are, like correcting «hlelo» to «hello».
To split the problem you look at the last letters of s and t. If they match, both are skipped and you move on to the earlier ones. If not, s is edited so they match, and you also move on. The state is [i, j]: how many letters of s and of t are left to resolve. dp[i, j] is the fewest changes to turn the first i letters of s into the first j of t. With s of n letters and t of m, the table has (n + 1) × (m + 1) cells.
When s[i − 1] and t[j − 1] are the same letter, no change is needed: both are skipped and dp[i, j] = dp[i − 1, j − 1]. That is why «cat» and «bat» are only 1 edit apart: the a and the t match and add nothing. Forgetting this case would give distances that are too large: treating each matching letter as a replacement would add 1 for each.
dp[i, j] depends on up, left and up-left. With a single row, going forward overwrites the up-left value, and going backward does not have the left one in time. The fix is to keep the up-left value in a variable, leftup, and walk forward. That lowers memory from O(nm) to O(m). The time is still O(nm): with 2 texts of 1,000 letters, 1 million cells.
