Tries (Prefix Trees)
A tree where each edge is a character and each path from the root spells a prefix, so insert, lookup and "any word starting with...?" cost O(key length), however many words are stored.
How it works
- Each node maps characters to children; an end flag marks where a whole word stops.
- Insert creates missing children, then sets
end; lookups stop at the first missing child. searchneeds the end flag;startsWithonly needs the path to exist.- Beats a hash set for prefix queries, autocomplete, sorted keys and multi-word search.
- Costs memory: one node per distinct prefix. Radix trees compress single-child chains.
Check yourself
Answer to mark it learned; your answers aren't scored.
A search box must suggest product names matching what the user has typed so far, on every keystroke, over 2 million names. Which structure fits best?
Go deeper
Solve it in Python 9
Full explanation
A trie stores strings by sharing prefixes. Each node holds children (char → node) and an end flag that marks where a whole word stops.
- insert(word): walk from the root, creating missing children, then set
end. - search(word): walk; fail on a missing child; succeed only if the last node has
end. - startsWith(prefix): the same walk, but reaching the last node is enough.
Each operation costs O(L) for a key of length L, independent of how many keys are stored. A hash set also does exact lookup in O(L) (hashing reads every character), but a trie answers prefix queries too, and a DFS over sorted children lists keys alphabetically.
Signals: prefix queries, autocomplete, "words that start with", spell check, or matching many words at once against a grid or stream: build the trie once and walk it as you explore. The cost is memory, one node per distinct prefix; radix trees merge single-child chains to save it.
Code Trie with insert, search and startsWith
class Node:
def __init__(self):
self.children = {} # char -> Node
self.end = False # a whole word stops here
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
if ch not in node.children:
node.children[ch] = Node()
node = node.children[ch]
node.end = True
def _walk(self, s: str): # node at the end of s, or None
node = self.root
for ch in s:
if (node := node.children.get(ch)) is None:
return None
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and node.end # a prefix alone is not a word
def starts_with(self, prefix: str) -> bool:
return self._walk(prefix) is not NoneReal example
Word search II. Find which of 10,000 words appear in a 12×12 letter grid as paths of adjacent cells. Searching each word separately repeats the grid DFS 10,000 times. Instead, insert every word into one trie and run one DFS from each cell, stepping down the trie as you step across the grid. Stop the moment the path is not a prefix of any word, and clear end on a found word so it is reported once.
Trade-offs +3 · −3
+ You gain
- Prefix queries in O(prefix length), with no scan over all keys.
- Common prefixes are stored once; a sorted DFS yields keys alphabetically.
- Prunes multi-word search: stop when the path is no word's prefix.
− You pay
- Memory heavy: one object per node, and in Python a dict per node.
- For exact lookups alone, a hash set is simpler and usually faster.
- Pointer chasing is cache-unfriendly compared with a sorted array and binary search.
Use it when
Prefix-based queries: autocomplete, "starts with", spell check, longest common prefix, or searching many words at once (grid word search, matching a dictionary against a stream).
Avoid it when
Only exact membership is needed (hash set), the key set is small and static (sorted list plus Binary search and search on the answer for the prefix range), or memory is tight.
Numbers to know 4
- insert, search, startsWith: O(L) for a key of length L, independent of the number of keys.
- Space: O(total characters) in the worst case, one node per distinct prefix.
- Array children: O(1) child lookup, but one slot per alphabet letter in every node (26 for a–z).
- Autocomplete: O(L) to reach the prefix node, plus the part of its subtree you visit.
Common pitfalls 4
searchreturns true for a mere prefix because theendcheck is missing.- Grid word search: not marking the cell before recursing (letters reused) or not restoring it after.
- Reporting a found word twice: clear its
endflag once it is found. - 26-slot arrays on mixed-case or Unicode input: index errors or wasted memory; use a dict.
Interview questions 2
Answer out loud first, then reveal.
When is a trie better than a hash set?Show answer
When the queries are about prefixes, not whole keys. A hash set answers "is cart present?" in O(L), like a trie, with less memory. But "which words start with ca?" forces it to scan every key, while the trie walks two nodes and enumerates that subtree. The same holds for searching many words at once: the trie lets me abandon a path as soon as it is nobody's prefix.
How would you return the top 3 autocomplete suggestions?Show answer
Walk to the prefix node, then collect words from its subtree. For alphabetical results, DFS the children in sorted order and stop at 3. For most-popular results, I store at each node the top 3 words of its subtree, updated on insert, so a query is O(L). That trades memory and slower writes for fast reads, the usual choice for typeahead, where reads dominate.