Tries
A trie (prefix tree) stores words one character per node. Words that start the same way share the same path from the root, so “does anything start with this prefix?” is answered by walking the prefix and nothing else.
insert: car, card, care, cat, dog (* = a word ends here)
root ├─ c │ └─ a │ ├─ r* "car" │ │ ├─ d* "card" │ │ └─ e* "care" │ └─ t* "cat" └─ d └─ o └─ g* "dog"When to reach for it
Section titled “When to reach for it”- The problem says prefix, autocomplete, or “starts with”.
- You answer many queries against one fixed set of words.
- You search a grid or text for many words at once and want to stop a path the moment no word starts that way (Word Search II).
- A hash set can say “is this exact word stored?” in O(L) but cannot say “does any word start with this?” without scanning every word. A trie does both in O(L).
- Cost: more memory than a set, since each node holds a child map.
Template
Section titled “Template”class Node: def __init__(self): self.children = {} # char -> Node self.is_word = False
def walk(root, s): node = root for ch in s: if ch not in node.children: return None # no stored word goes this way node = node.children[ch] return node # prefix exists; check node.is_word for a full wordInsert is the same walk, creating missing nodes and setting is_word at the end.
Problems in this guide
Section titled “Problems in this guide”- Implement Trie (Prefix Tree) — insert, search and prefix check on a char-by-char tree