Tries (Prefix Trees)
Store strings character by character in a tree for fast prefix lookups, autocomplete, word search and XOR maximisation.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Binary Trees and Traversals, Hash Tables and Hashing Patterns
A trie stores a set of strings where each edge is a character and each path from the root spells a prefix. Insert and search cost O(L) for a word of length L, independent of how many words are stored.
Structure
Each node holds children (an array of 26 for lowercase letters, or a hash map for larger alphabets) and a flag marking the end of a word. Optionally store a count of words passing through the node to answer "how many words start with this prefix".
Operations
- insert(word), search(word), startsWith(prefix).
- Delete by decrementing counts or unmarking end flags.
- Collect all words under a node for autocomplete.
Patterns
- Prefix queries: autocomplete, longest common prefix, replace words with their root.
- Word Search II: build a trie of the dictionary and DFS the grid once, pruning when the current path is not a prefix. Far faster than searching each word separately.
- Bitwise trie: store numbers bit by bit (from the highest bit) to find the maximum XOR pair in O(n * 32).
- Wildcard search ("b.d") with DFS over children.
Trade-offs
Tries can use a lot of memory (26 pointers per node). Hash sets are simpler when you only need exact lookups; tries win when prefixes matter.
Key concepts
- Trie node design
- Insert, search, startsWith
- Prefix counts
- Autocomplete
- Trie + DFS (Word Search II)
- Bitwise trie for max XOR
Mini project
Build a small autocomplete CLI backed by a trie that suggests the top 5 words for a prefix, then solve: Implement Trie, Design Add and Search Words, Replace Words, Word Search II, and Maximum XOR of Two Numbers in an Array.
Check yourself
Why is Word Search II with a trie much faster than running Word Search separately for every dictionary word?
Free resources
- Trie data structure (GeeksforGeeks)
- Aho-Corasick and tries (cp-algorithms)
- LeetCode Explore (LeetCode)