Prefix Search
Step 1 of 9
Three words are stored. The user has typed nothing yet, so every one of them is still a candidate.
The Idea
Autocomplete asks a different question from "is this a word?". It asks "what starts with this?".
Walk the prefix once — that costs one hop per typed character. The node you land on is the root of a subtree holding exactly the words with that prefix, so gathering the suggestions never touches the rest of the dictionary.
Real-World Example
A phone keyboard suggesting words after three letters. It cannot rescan 200,000 words between keystrokes, so it keeps the position it reached for "cat" and, on the next key, takes one more hop instead of starting over.
The Code
Your turn
Fill in the blank.
trie = {"a": {"t": {"$": 1}}}
node = trie
for ch in "ax":
node = node.get(ch)
if node ___ None:
break
print(node) # NoneMini quiz
1 / 3