Trie (prefix tree)
medium 20 minA trie (pronounced "try") is a tree that stores strings one character per level, so words with the same opening letters share the same path from the root.
See it run
Insert, search, starts_with and delete on a prefix tree where words share their opening letters, then autocomplete straight from the tree.
Operations
Insert
Walk down one letter at a time, creating any missing child, then mark the last node as the end of a word.
Step 1 of 9
An empty trie
A trie starts as a single root node with no letter and no children. Every word will be a path down from it. We insert cat, car, card and care.
Step 1: An empty trie
class TrieNode: def __init__(self): self.children = {} # letter -> TrieNode self.is_end = False # True if a word ends heredef insert(root, word): node = root for ch in word: if ch not in node.children: node.children[ch] = TrieNode() # new branch node = node.children[ch] # step down one letter node.is_end = True # mark the last letter- Time
- O(L)
- Space
- O(L) new nodes at most
- vs hash set add
- O(L) to hash
- shared prefix
- reused, not copied
Say both halves out loud: create a child if missing, step into it, and after the loop mark is_end. Forgetting the mark is the classic bug.
In the real world
The same trie doing real jobs. Pick one and step through it.
The old Google preset: popular queries live in a trie with a search count on each end node, and every keystroke moves one level down.
Step 1 of 7
The query trie
Stored queries include how to code, how to cook pasta, how to learn python, how to make money, how are you and weather today. To fit the screen, letters after a branch are merged into one box; a real trie keeps one node per character, spaces included.
Step 1: The query trie
def suggest(root, typed, k=3): node = find_node(root, typed) # one hop per keystroke if node is None: return [] # "No suggestions" found = [] def dfs(n, text): if n.is_end: found.append((n.freq, text)) # frequency stored on the end node for ch, child in n.children.items(): dfs(child, text + ch) dfs(node, typed) found.sort(reverse=True) # most searched first return [q for _, q in found[:k]]Common mistakes
The bugs interviewers watch for, with the fix beside each.
Search returns True for a prefix
criticalReaching the last letter only proves the path exists. Without checking is_end, search('ca') says True after inserting only cat.
Wrongdef search(root, word): node = root for ch in word: if ch not in node.children: return False node = node.children[ch] return True # this is starts_with, not searchRightdef search(root, word): node = root for ch in word: if ch not in node.children: return False node = node.children[ch] return node.is_end # the word must end exactly hereChildren dict shared by every node
criticalA class-level dict is created once and shared by all instances, so every node sees every child and the trie becomes one tangled node.
Wrongclass TrieNode: children = {} # one dict for ALL nodes is_end = FalseRightclass TrieNode: def __init__(self): self.children = {} # a fresh dict per node self.is_end = FalseForgetting to mark the end on insert
majorWithout the final flag no word is ever found by search. Marking every node on the way down is the opposite bug: every prefix becomes a word.
Wrongdef insert(root, word): node = root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end = True # marks c, ca and catRightdef insert(root, word): node = root for ch in word: node = node.children.setdefault(ch, TrieNode()) node.is_end = True # only the last letterDelete removes nodes other words still use
majorCutting the whole path of car would also destroy card and care. Prune a node only when it is not an end and has no children.
Wrongdef delete(root, word): # drop the first letter's subtree root.children.pop(word[0], None) # deletes every c-wordRightdef delete(node, word, i=0): if i == len(word): node.is_end = False return not node.children child = node.children.get(word[i]) if child and delete(child, word, i + 1): del node.children[word[i]] return not node.is_end and not node.children return FalseArray index for characters outside a to z
minorA 26-slot array assumes lowercase letters. An uppercase letter, digit or space gives a negative or too-large index. Normalise input or use a dict.
Wrongidx = ord(ch) - ord("a")node = node.kids[idx] # 'A' gives -32: wrong slot or IndexErrorRightch = ch.lower()if not ("a" <= ch <= "z"): raise ValueError(ch) # or switch to a dict of childrennode = node.kids[ord(ch) - ord("a")]
Interview tips
How to explain it
- A trie is a tree where each edge is a letter and each root-to-node path spells a prefix. Words with a common prefix share nodes.
- Every operation is O(L) in the word length L and independent of how many words are stored.
- Draw cat, car, card and care: four words, one shared c-a path, r marked and also a parent.
- Name the node layout: a dict of children (flexible, small) or a 26-slot array (fast index, more memory).
When to reach for a trie
- Prefix questions: autocomplete, starts_with, count words with a prefix.
- Many words searched at once, such as Word Search II: one DFS guided by a trie of all words.
- Longest common prefix, shortest root replacement, longest prefix match (IP routing).
- Wildcard search where '.' matches any letter: branch over all children at that position.
Memory tricks
- TRIE: Tree for Retrieval, Insert char by char, End marks the word.
- Search checks is_end; starts_with does not. That is the only difference.
- Delete prunes a node only if it is not an end and has no children.