All episodes · From a List to Your Map App · Episode 23

How Spell Check Guesses Your Word: Edit Distance

Pressing play loads the video from YouTube.

Type "speling" and your phone suggests "spelling". It counts how many small edits turn one word into another, and suggests the closest.
We meet the three kinds of edit (insert, delete, swap), then build a table to find the fewest edits from "kitten" to "sitting": each cell looks only at its left, upper and upper-left neighbors, and the bottom-right corner says three. Walking back from the corner shows which three. The same table powers spell checkers, shows which lines changed between two versions of a file, and compares DNA sequences.

Every animation in this video is drawn by code, and the narration is an AI voice.

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.

Buy the Developer a Coffee

Entirely up to you: it works the same either way.

Every cup turns into the next update.

WeChat Pay QR code
WeChat Pay
Alipay QR code
Alipay
PayPal QR code
PayPal