Tries: prefix trees for words
A tree where each edge is a letter, so words that share a prefix share a path. Autocomplete, spell checkers and word-search problems.
In short
A trie stores words letter by letter along a path from the root; words with a common prefix share nodes. Insert, search and prefix queries all cost O(L) for a word of length L, independent of how many words are stored.
Why not just a hash set?
A hash set answers "is this exact word stored?" in O(L). It can't answer "which words start with ca?" without scanning everything. A trie answers prefix questions by simply walking down.
1class Trie:2 def __init__(self):3 self.root = {}4 def insert(self, word):5 node = self.root6 for ch in word:7 node = node.setdefault(ch, {})8 node["$"] = True9 def starts_with(self, prefix):10 node = self.root11 for ch in prefix:12 if ch not in node: return False13 node = node[ch]14 return True
Variables
Operations
- Insert: walk down, creating missing children, then mark the last node as the end of a word.
- Search (whole word): walk down; succeed only if the last node is marked as a word end.
- Starts with (prefix): walk down; succeed if the path exists, no end marker needed.
- Autocomplete: walk to the prefix node, then DFS below it to list the words.
| Trie | Hash set | |
|---|---|---|
| Exact lookup | O(L) | O(L) |
| Prefix query | O(L) | O(n·L) scanning |
| Space | Shared prefixes, but one node per letter | One entry per word |
| Sorted listing | DFS visiting children in order | Needs sorting |
Key takeaways
- 01A trie shares prefixes: one path per letter from the root.
- 02Insert, search and prefix queries are O(L).
- 03Mark word ends: "car" can be a prefix of "card".
- 04Reach for a trie when the problem is about prefixes.
Check your understanding
1 of 3
What does a trie do better than a hash set?
Related topics
Hash maps
A hash map stores key → value pairs and finds any key in O(1) on average. Whenever a loop keeps asking "have I seen this before?", a hash map usually turns O(n²) into O(n).
8 min read →Traversals
A tree is a node with up to two subtrees, so most problems are recursion: solve the left, solve the right, combine. DFS (inorder, preorder, postorder) uses the call stack; BFS (level order) uses a queue. All visit each node once: O(n); space is O(h) for DFS and O(width) for BFS.
9 min read →