Tries
Store strings in a prefix tree for fast prefix search, autocomplete and word games, and use binary tries for maximum XOR problems.
Intermediate · about 5 hours · difficulty 3/5
Learn first: Backtracking, Hashing with Maps and Sets
A trie stores strings character by character so that common prefixes share nodes. Insert and search take O(length of word), independent of how many words are stored.
Implementation
Each node holds up to 26 children (array or map) and an end-of-word flag. Add counters (prefix count, end count) to support counting and deletion.
Key patterns
- Implement Trie (insert, search, startsWith).
- Autocomplete and Search Suggestions System.
- Word Search II: build a trie of words and DFS the grid once, pruning dead prefixes.
- Longest Word in Dictionary, Replace Words, Count distinct substrings (insert all suffixes).
- Binary trie for XOR: insert numbers bit by bit from the most significant bit; for each query, greedily go to the opposite bit (Maximum XOR of Two Numbers in an Array, Maximum XOR With an Element From Array).
Pitfalls
- Memory: 26 pointers per node times total characters can be large. Use a map per node if the alphabet is big or sparse.
- Forgetting the end-of-word flag, so "app" is reported present after inserting only "apple".
- In Word Search II, not removing found words, causing duplicates and TLE.
You are ready to move on when you can implement a trie with prefix counts and solve Maximum XOR of Two Numbers with a binary trie.
Key concepts
- Trie node structure
- Insert, search, startsWith
- Prefix and end counters
- Trie plus DFS on a grid
- Binary trie for maximum XOR
- Map vs array children
Mini project
Implement a trie class with insert, search, startsWith, countWordsEqualTo and erase, then solve: Implement Trie (Prefix Tree),Longest Word in Dictionary, Replace Words, Search Suggestions System, Word Search II, Maximum XOR of Two Numbers in an Array. Log time and pattern.
Check yourself
Why is a trie faster than a hash set for 'does any stored word start with this prefix?' queries?
Free resources
- takeUforward trie series (takeUforward)
- NeetCode roadmap: Tries (NeetCode)
- LeetCode problem set (LeetCode)