Advanced 12 min

Tries and prefix search

A trie stores words by sharing the path for their common starting letters.

How it works

Follow one character per edge. To add cart after car, reuse the first three edges and create only the edge for t. The r node still marks car as a complete stored word. Adding that marker is what lets one saved word also be the prefix of another.

Walk through an example

The words car and cart share c → a → r. Mark the r node as the end of car, then add a t node marked as the end of cart.

What to watch for

A prefix path may exist without marking a whole word. Lookup needs the end marker, while a prefix query only needs the path.

Code example

def insert(root, word):
    node = root
    for letter in word:
        node = node.setdefault(letter, {})
    node[None] = True

Check your understanding

Is ca a stored word, a prefix, or both?

See the example and explanation
Worked example
Given The trie contains car and cart only.
Answer A prefix only.

The path c → a exists, but there is no end marker at the a node.

Open practice problem
Next lessonUnion-find and connected groups