Transcript
Type speling, and your phone suggests spelling. How does it know which word you meant? It counts how many small edits turn one word into another, and suggests the closest. Today: edit distance.
There are three kinds of edit: insert a letter, delete a letter, or swap one letter for another. Speling needs just one: insert an l. Kitten into sitting needs three: k to s, e to i, and a g at the end.
To find the fewest edits, build a table, with kitten down the side and sitting across the top. Each cell holds the fewest edits between the two beginnings so far, and it only looks at three neighbors: left, above, and above-left. If the letters match, copy the diagonal for free. If not, take the smallest of the three, plus one. Fill it row by row, and the bottom-right corner says three.
Walk back from the corner to see which three: swap k for s, swap e for i, and insert a g.
A spell checker compares what you typed with words in its dictionary and offers the ones with the smallest distance. The same table can show which lines changed between two versions of a file, or compare two DNA sequences.
One table, three neighbors per cell, and the answer waits in the corner. That's dynamic programming at work. Next time: try, back up, and try again, and problems that may have no fast answer at all. See you there.
Next episode: backtracking. Try, back up, try again, and meet problems that may have no fast answer at all.