10. Tries (Prefix Trees)
A tree of characters where each path from the root spells a prefix. Lookups cost O(length of the word), independent of how many words are stored. Used for autocomplete and word games.
How it works
Each trie node maps a character to a child node and has a flag saying whether a word ends there. Words that share a prefix share the path: car, cat and cart all reuse the c -> a nodes.
- insert: walk the characters, creating missing children, then set the end-of-word flag.
- search(word): walk the characters; succeed only if the path exists and the flag is set.
- startsWith(prefix): succeed if the path exists at all.
Diagram
graph TD
root["root"]
t_d["d"]
root --> t_d
t_c["c"]
root --> t_c
t_ca["a"]
t_c --> t_ca
t_cat["t - end of cat"]
t_ca --> t_cat
t_car["r - end of car"]
t_ca --> t_car
t_cart["t - end of cart"]
t_car --> t_cart
t_do["o"]
t_d --> t_do
t_dog["g - end of dog"]
t_do --> t_dog
Step-by-step trace
Input: Insert car, cat, cart, dog; then look up car, ca and cow.
| Operation | Path walked | New nodes | Result |
|---|---|---|---|
| insert car | c -> a -> r | 3 | end-of-word mark set |
| insert cat | c -> a -> t | 1 | end-of-word mark set |
| insert cart | c -> a -> r -> t | 1 | end-of-word mark set |
| insert dog | d -> o -> g | 3 | end-of-word mark set |
| look up car | c -> a -> r | 0 | search=True, startsWith=True |
| look up ca | c -> a | 0 | search=False, startsWith=True |
| look up cow | c | 0 | stops after ācā: no child āoā |
Result: ca is a prefix but not a stored word, so search is False while startsWith is True.
Complexity
| Operation | Time | Space |
|---|---|---|
| Insert / search / startsWith (word length L) | O(L) | O(L) new nodes for insert |
| Total space for all words | - | O(total characters) |
Python reference implementation
class TrieNode:
def __init__(self):
self.children = {}
self.is_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node, created = self.root, 0
for ch in word:
if ch not in node.children:
node.children[ch] = TrieNode()
created += 1
node = node.children[ch]
node.is_word = True
return created
def _walk(self, text):
node = self.root
for ch in text:
node = node.children.get(ch)
if node is None:
return None
return node
def search(self, word):
node = self._walk(word)
return node is not None and node.is_word
def starts_with(self, prefix):
return self._walk(prefix) is not None
Common mistakes and tips
- Forgetting the end-of-word flag makes every prefix look like a stored word.
- A dict of children is simplest; a fixed array of 26 is faster for lowercase-only input.
- Word search on a grid: put the dictionary in a trie and prune DFS paths that leave the trie.
The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.
| Previous: Heaps and Priority Queues | Next: Fenwick Tree (Binary Indexed Tree) |