Trie (Prefix Tree)
O(L) per op
A tree of characters; each path spells a prefix. Walk character by character to insert/search.
0/12 solved
Recognise it
The signal
Many words with prefix queries: autocomplete, startsWith, Replace Words, word search on a grid, or max XOR pair.
1Brute force
Compare the query with every word.
2The observation
Repeated prefix comparisons: shared prefixes are stored once.
3Why it works
A node at path p exists iff some inserted word has prefix p; end flags mark complete words.
Reach for it when
- +Prefix queries — autocomplete, 'startsWith', dictionary lookups, shortest root word (Replace Words).
- +Many words searched repeatedly, or word search on a grid where prefix-pruning saves huge time.
- +Bitwise tries for maximum XOR (treat each number as a 32-bit 'string').
Not when
- ×Only exact membership, no prefixesuse Hash set
- ×Few short strings, queried onceuse Direct comparison; a trie isn't worth building
- ×Fuzzy / edit-distance matchinguse Trie + DP; a plain trie won't do it alone
- ×Substring (not prefix) queries over one textuse Suffix array, or Aho-Corasick for many patterns
Intuition
A trie (prefix tree) stores strings by their shared prefixes, letter by letter. The root is empty; each edge is a character; walking a path spells a prefix. "cat", "car", "card" share the path c→a, then branch at t / r, and "card" extends "car" with a final d. An isEnd flag on a node marks "a real word ends here."
Read the full intuition
Why not just a hash set? Because a set answers "is this exact word present?" but a trie also answers "is any word starting with this prefix present?" in O(length) — perfect for autocomplete, dictionaries, and walking a grid letter by letter (Word Search II) where you prune the instant the current path isn't a prefix of any word.
The node is tiny:
class Node: children = {} # char -> Node
is_end = FalseInsert: walk/create a child per character, set is_end at the last. Search: walk children; missing child → not present; at the end, check is_end for a full word or just "reached" for a prefix.
Key idea
Cost is O(L) per operation (L = word length), independent of how many words you've stored — that's the win over scanning a list. For lowercase-only problems an array
children[26]is faster than a hash map.
Why it costs what it costs
Time O(L) per op. insert/search walk one node per character of the word, independent of the number of stored words.
Space O(N·L). worst case a node per character across all inserted words (shared prefixes save space).
Practice
- Implement Trie (Prefix Tree)FoundationFoundationAmazon, GoogleMedium
- Replace WordsApply it · Shortest root prefix for each word.Apply itUber, GoogleMedium
- Search Suggestions SystemOne change · Top 3 suggestions per prefix.One changeAmazon, UberMedium
- Design Add and Search Words Data StructureTwists · Wildcard '.'.TwistsMeta, AmazonMedium
- Maximum XOR of Two Numbers in an ArrayBranches · Bits as characters.BranchesCitadel, GoogleMedium
- Word Search IICombine · Trie guides a grid DFS.CombineAmazon, GoogleHard
- Word CombinationsCombine · Trie + DP over positions.CombineCSESMedium
- Maximum XOR With an Element From ArrayMastery checkMastery checkHard
- Word BreakSnowflake, CitadelMedium
- Maximum Xor SubarrayCSESMedium
- Command Autocomplete from HistoryUberOAMedium
- Maximum Genetic Difference QueryHard
Pitfalls
Classic bugs
- !No
is_endflag: 'app' matches when only 'apple' was inserted. Search needsis_end, startsWith only needs the node. - !Wildcard
'.'(Add and Search Words): recurse into all children, not just one. - !Word Search II: DFS the grid against a trie of words, and remove found words to avoid duplicates and dead branches.
- !Memory: hash-map children are flexible but heavy; use a
[26]array for fixed lowercase.
Go deepervariants and techniques · 5 combinations · resources
Variants and techniques
- Aho-Corasick AutomatonBuild a trie of patterns plus KMP-style failure links so one pass over the text finds all occurrences of all patterns.
- Binary (XOR) TrieInsert numbers bit by bit (MSB first) into a trie and greedily walk the opposite bit to maximise (or minimise) XOR with a query.
- Basic prefix treeinsert / search / startsWith with is_end flags. Implement Trie.
- Wildcard matchingOn '.', recurse over every child. Add and Search Words.
- Shortest root replacementInsert roots; for each word, walk until the first is_end node. Replace Words.
- Grid + trie DFSBuild a trie of words, DFS the board following trie edges, collect at is_end. Word Search II.
- Bitwise trie (XOR)Insert numbers as 32 bits MSB→LSB; greedily go to the opposite bit to maximize XOR. Maximum XOR of Two Numbers.
Combinations
Trie (Prefix Tree)+Backtracking
find all dictionary words in a grid
- Trie (Prefix Tree):
- prefix pruning for all words at once
- Backtracking:
- grid path enumeration with undo
Trie (Prefix Tree)+1D / Fibonacci-style
word break / count segmentations with a big dictionary
- Trie (Prefix Tree):
- enumerates dictionary words starting at i in one walk
- 1D / Fibonacci-style:
- counts/decides segmentations
Binary (XOR) Trie+Offline Query Processing
max XOR with an element <= m_i
- Binary (XOR) Trie:
- max XOR with inserted numbers
- Offline Query Processing:
- sorts queries by limit so only allowed numbers are inserted
maximum XOR of a subarray
- Binary (XOR) Trie:
- maximises XOR with an earlier prefix
- Prefix Sum:
- subarray XOR = prefix XOR pair
Binary (XOR) Trie+Tree DFS (Paths & Recursion)+Offline Query Processing
max XOR of a value with any ancestor of a node, many queries
- Binary (XOR) Trie:
- the max XOR against values on the root path (counts per trie node allow removal)
- Tree DFS (Paths & Recursion):
- on entry insert the node's value, on exit remove it
- Offline Query Processing:
- attach the queries to their nodes