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.
Remember it
The few things worth knowing cold, and how to make them stick.
Memory hook
TRIE: Tree for Retrieval, Insert char by char, End marks the word.
A phone book is already a trie. Names are grouped by first letter, then by second letter inside that, and so on. To find someone you never read the whole book: you follow the path letter by letter, and every name that starts the same way sits in the same section.
Cheat sheet
- Node
- children + is_end
- insert
- O(L)
- search
- O(L), checks is_end
- starts_with
- O(m), no end check
- delete
- O(L), prune non-end leaves
- Autocomplete
- O(m + k)
- Space
- at most 1 node per character
- Array node
- 26 slots, fixed alphabet
- Dict node
- any alphabet, only real children
Spot it when you see
- Prefix, starts with, autocomplete, typeahead, suggestions.
- Many words searched in one grid or one text.
- Shortest root, longest common prefix, longest prefix match.
- Wildcard patterns where a dot matches any letter.
- Maximum XOR of two numbers: a trie on bits.
Tricks that stick
- TRIE = Tree, Retrieval, Insert char by char, End marker.
- Search ends with is_end; starts_with ends with True.
- Insert pattern: create if missing, step down, mark the last.
- Delete prunes only nodes that are not ends and have no children.
- Autocomplete = walk the prefix, then DFS.
Do not forget
- Returning True from search without checking is_end.
- A class-level children dict shared by every node.
- Marking is_end on every node during insert.
- Deleting nodes that other words still use.
- Assuming lowercase a to z with an array when input has other characters.
- Calling trie lookups O(1): they are O(L).