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

Finding a Word in Text Without Looking Back: KMP and Tries

Pressing play loads the video from YouTube.

The simple way to find a word slides it along the text one step at a time, and on some texts it reads the same letters again and again.
We count every comparison: 23 for "cocoa" in an 11-letter text the simple way, 14 with KMP, which lines up what already matched and never steps back in the text. A small table, worked out from the word alone, says how far to slide. For a million letters, that's at most about two million comparisons instead of up to a billion. Then we build a trie, one letter per level, and see how a search box finds every word that starts with the letters you've typed.

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

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.

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