Lesson 17 of 40Trees and graphs
Tries
Build a prefix tree that answers "is this a word?" and "does anything start with this?" in time set by word length.
Type "pyt" into a search box and you instantly see "python", "pytest", "pytorch". The suggestions do not come from scanning every word in a dictionary. They come from a trie (say "try"), a tree built so that every word sharing a prefix shares a path.
Tries show up in autocomplete, spell checkers, IP routing tables, and in interview problems like word search and "replace words with their root". Once you can build one, those problems become a walk down a tree.
One letter per step
A trie stores words character by character. The root is empty. Each link out of a node is one letter, so the path from the root to any node spells a prefix. A node also carries a flag, usually called is_end, that says "a complete word stops here".
Here is a trie holding car, cart, cat and dog. To make it readable, each node is labelled with the prefix its path spells. Nodes marked word have is_end = True.
Every lookup starts at the empty root.
Notice what the work depends on. Looking up cart takes four steps whether the trie holds four words or four million. The cost is set by the length of the word, not the number of words.
is_end flag? Why not just check that the path exists?The code
A node is a map of children plus the flag. Insert walks down, creating missing children. Search and prefix check share one walk.
Press Run (⌘ Enter) to see what happens.Press Run (⌘ Enter) to see what happens.What does this print?
t = Trie()
t.insert("app")
t.insert("apple")
print(t.search("appl"), t.starts_with("appl"), t.search("app"))Autocomplete: collect everything below a node
To suggest completions for a prefix, walk to the prefix node, then do a depth-first search from there, collecting every node with is_end set. The path you took spells each word.
def complete(trie, prefix):
node = trie._walk(prefix)
if node is None:
return []
words = []
def dfs(n, path):
if n.is_end:
words.append(path)
for ch, child in sorted(n.children.items()):
dfs(child, path + ch)
dfs(node, prefix)
return words
# complete(t, "ca") -> ['car', 'cart', 'cat']A production autocomplete also stores a popularity count on each word end and keeps only the top few per node, so it does not have to explore a huge subtree on every keystroke.
Put the autocomplete steps in order.
- Tap the steps below in the right order.
Cost and the memory tradeoff
Let L be the length of the word or prefix.
| Operation | Time | Why |
|---|---|---|
insert(word) | O(L) | One step per letter |
search(word) | O(L) | One step per letter, then check the flag |
starts_with(prefix) | O(L) | Same walk, no flag check |
| Build from n words | O(total letters) | Each letter inserted once |
Compare with a plain set of words. word in my_set is also about O(L) (it has to hash the string), so for exact lookups a set is simpler and just as fast. The trie wins when the question is about prefixes: "does anything start with pre?" on a set means checking every word.
The price is memory. Each node is an object with its own dictionary, which in Python is a few hundred bytes. A trie of 100,000 English words can have several hundred thousand nodes. Shared prefixes help, but a trie usually uses more memory than the raw strings. Two common fixes: store children in a fixed array of 26 slots when the alphabet is small, or compress chains of single-child nodes into one node (a radix tree).
Wildcard search: Add and Search Words
A common follow-up: search must accept . as "any one letter", so .ad matches bad, dad and mad. Exact letters still walk one child. A dot has to try every child at that depth, which turns the walk into a depth-first search. Each branch either fails fast (the letter is missing) or reaches the end of the pattern and checks the end flag.
This version stores nodes as plain dicts with a "$" key as the end marker, a compact style you will see in many interview answers. The idea is the same as TrieNode.
Press Run (⌘ Enter) to see what happens.Cost: with no dots it is still O(L). Each dot multiplies the work by up to the alphabet size, so a pattern of all dots can visit every node at that depth: O(26^L) in the worst case, bounded by the size of the trie. Interviewers ask this. The honest answer is "O(L) for plain words, and up to the whole trie for patterns full of dots". Two details matter in the code: skip the "$" marker when iterating children (it is not a letter), and use any, which stops at the first match instead of exploring every branch.
Word Search II: trie plus backtracking
Given a letter grid and a list of words, return every word that can be traced through adjacent cells without reusing a cell. The naive approach runs the single-word grid search from Backtracking once per word. With 10,000 words, that is 10,000 full grid searches, and most of them retrace the same prefixes.
Build a trie of the words instead and run one DFS from each cell, walking the grid and the trie together. If the grid letter is not a child of the current trie node, no word continues that way, so the branch dies at once. One walk checks every word at the same time.
Three refinements make it fast enough for the large test cases:
- Store the word at its end node (
node.word = "oath") instead of rebuilding the string from the path. - Clear it once found (
node.word = None), so a word that appears twice in the grid is reported once. - Prune emptied branches. After exploring from a node, if it has no children and no word left, delete it from its parent. Later searches never walk into a part of the trie that has nothing left to find. On boards with many matches this is the difference between passing and timing out.
Press Run (⌘ Enter) to see what happens.The # marking and the restore after the loop are the grid version of choose and un-choose, covered in Backtracking. The second assert checks that the board is left exactly as it was given, which an interviewer may ask about: callers rarely expect a search to change their data.
Deleting a word and cleaning up
delete looks simple: walk to the end node and set is_end = False. That is correct, and many production tries do only that. But it leaves dead nodes behind. Delete cart and the t node stays, holding no word and leading nowhere. A trie that sees many inserts and deletes (a cache of active session keys, say) slowly fills with dead branches.
The full delete removes nodes on the way back up, but only while each node is both not a word end and has no remaining children. Recursion fits, because the decision for each node depends on what happened below it.
Press Run (⌘ Enter) to see what happens.The trie starts with car, cart and cat, and the root counts as a node. What does the block above print?
print(sizes)
A Python dict that loses its keys does not shrink its internal table straight away, so the memory win from deleting nodes comes from dropping whole node objects, not from emptying their dicts.
Children as a dict or as a 26-slot array
The node shape is a real design choice, and interviewers like to hear you weigh it.
| Dict / Map of children | Fixed array of 26 | |
|---|---|---|
| Find a child | Hash the letter, then look up | children[ord(ch) - 97], one index |
| Memory per node | Grows with the number of children | Always 26 slots, mostly empty deep in the trie |
| Alphabet | Any: Unicode, digits, URL path parts | Must be small and known up front |
| Iterate children in order | Sort the keys | Already in alphabetical order |
Most trie nodes, especially deep ones, have one or two children. So for a large dictionary the array wastes most of its slots, and the dict usually wins on memory. The array wins on speed for small fixed alphabets and gives sorted iteration for free, which is handy for autocomplete. In a lower-level language the array of pointers costs eight bytes per slot on a 64-bit machine even when empty, so 26 slots is roughly 200 bytes of mostly nothing per node. In Python, each node is an object either way, so the gap is smaller than you might guess. Measure with your own data before deciding. If memory really matters, the bigger win is structural: a radix tree, or a sorted array of strings searched with binary search.
Binary tries: Maximum XOR of Two Numbers
A trie does not have to hold letters. Store each number as its bits, highest bit first, and each node has at most two children: 0 and 1. This binary trie solves "find the maximum a ^ b over all pairs" in O(n · bits) instead of O(n²).
The greedy idea comes from Bit Manipulation's rule that XOR is 1 where bits differ. The highest bit matters most: getting a 1 at bit 30 beats any combination of lower bits. So for each number x, walk down the trie and at every level try to go to the opposite bit of x. If that child exists, this bit of the XOR is 1. If not, you are forced along the same bit and this XOR bit is 0.
The trie holds 2, 5 and 7 as 3-bit numbers. Find the best partner for x = 2, which is 010.
Press Run (⌘ Enter) to see what happens.bits=31 covers non-negative 32-bit integers. The else branch never fails: every stored number has a path of full length, so if the opposite child is missing, the same-bit child must exist. Binary tries also answer "maximum XOR with an element no larger than m" (sort the queries and insert numbers as you go) and appear in routing tables, where IP prefixes are stored bit by bit and a lookup finds the longest matching prefix.
How to recognise it
Common mistakes:
- Forgetting
is_end, so every prefix counts as a word. - Marking only leaves as word ends.
carmust be marked even thoughcartcontinues below it. - Creating new nodes during
search. Lookups must never change the trie; use a read-only walk. - Using a trie when a set would do. If nothing in the problem mentions prefixes, a set is simpler.
Implement a Trie
Build a prefix tree (trie) that stores lowercase words.
It needs three methods:
insert(word)adds a word.search(word)returnsTrue/trueonly if that exact word was inserted.starts_with(prefix)(Python) /startsWith(prefix)(TypeScript) returns whether any inserted word begins withprefix.
t = Trie()
t.insert("car")
t.search("car") → True
t.search("ca") → False ("ca" is only a prefix)
t.starts_with("ca") → True
t.insert("ca")
t.search("ca") → TrueEvery method should run in O(length of the word), whatever the number of words stored.
- trie
- A tree where each link is one character and each root-to-node path spells a prefix.
- is_end flag
- Marks that a complete inserted word ends at this node, so prefixes are not mistaken for words.
- O(L) lookup
- Trie operations cost one step per character of the word, independent of how many words are stored.
- prefix query
- A question like "does any word start with abc?" A trie answers it by walking to the prefix node.
- radix tree
- A compressed trie where chains of single-child nodes are merged to save memory.
- wildcard search
- A trie lookup where
.matches any letter, so the walk branches into a DFS over every child at that depth. - trie pruning
- Deleting a trie node once nothing is left to find below it, so later searches stop early. Key to Word Search II.
- binary trie
- A trie over the bits of numbers, high bit first, with at most two children per node. Finds maximum XOR greedily.