Transcript
To find shells in she sells sea shells, the simple way lines the word up, compares letter by letter, and slides one step on every miss. Here that's twenty-six comparisons. But on some texts, it reads the same letters again and again. Today: finding a word without looking back.
Now search for cocoa in this text. The first four letters match, then a meets c: a miss. The simple way slides one step and starts over at the word's first letter, so it reads the same letters again and again. Twenty-three comparisons for an eleven-letter text. At worst, it's the text's length times the word's length.
But look at what just matched: c-o-c-o. It ends in c-o, and c-o is exactly how the word starts. So slide the word two steps to line those up, and carry on from the same spot in the text. We never step back. How far to slide depends only on the word, so we work it out once, in a little table, before we start. This is the KMP algorithm, named after its three inventors. Here it needs fourteen comparisons instead of twenty-three.
Because the text pointer only moves forward, KMP never needs much more than twice the text's length in comparisons. For a million letters and a thousand-letter word, that's at most two million comparisons, instead of up to a billion.
Now a different search: as you type, show every word that starts with those letters. For that, store the words in a trie, one letter per level. Type c, then a, and you're standing on the branch that holds can, cap, car, card and cat. Every word below that spot is a suggestion, and getting there took just two steps.
Don't re-read letters you've already matched, and for word beginnings, let a tree do the walking. That's how search stays fast. Next time: graphs, points joined by lines, from mazes to maps. How do you store one, and visit every point? See you there.
Next episode: graphs, points joined by lines, and how to store one and visit every point.