Skip to content
BytePatterns

Prefix Search

Tries: lesson 2 of 4

Walk to the prefix once, then everything below it is the answer.

Lesson 2 of 4 · 5 min

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

trie = {"c": {"a": {"r": {"$": 1, "t": {"$": 1}}, "t": {"$": 1}}}}
def walk(prefix):                  # O(len(prefix)) — dictionary size is irrelevant
    node = trie
    for ch in prefix:
        if ch not in node: return {}
        node = node[ch]
    return node

def collect(node, so_far, out):
    if "$" in node: out.append(so_far)
    for ch in node:
        if ch != "$": collect(node[ch], so_far + ch, out)
    return out

print(collect(walk("ca"), "ca", []))   # every word under the 'ca' branch

Python

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)   # None

Mini quiz

1 / 3

How long does it take to reach the node for a prefix of length P?

New lessons land every few weeks

Leave an address and we will tell you when the next one is up. That is the only reason we will use it.

One address, stored so we can email you. Nothing else, ever.