Trie Pattern
Prefix problems — autocomplete, word search on a board, replace words, and XOR maximisation with a binary trie.
Use a trie when a problem asks about prefixes across many strings, or when you need to search many words at once. Each node is a prefix; walking down the trie runs the search for every word with that prefix at the same time.
Trie for cat, car, dog. Green nodes end a word.
When to use this pattern
- "Starts with", autocomplete, longest common prefix, word suggestions.
- Searching a grid or text for many dictionary words at once (Word Search II).
- Replacing words with their shortest root, or matching wildcard patterns (
.). - Maximum XOR of pairs: a trie over the bits of the numbers.
Template
class Trie {
Trie[] next = new Trie[26];
String word; // set on the node that ends a word
void insert(String w) {
Trie n = this;
for (char ch : w.toCharArray()) {
int i = ch - 'a';
if (n.next[i] == null) n.next[i] = new Trie();
n = n.next[i];
}
n.word = w;
}
boolean startsWith(String p) {
Trie n = this;
for (char ch : p.toCharArray()) {
n = n.next[ch - 'a'];
if (n == null) return false;
}
return true;
}
}class Trie:
def __init__(self):
self.root = {}
def insert(self, w):
n = self.root
for ch in w:
n = n.setdefault(ch, {})
n["$"] = w # end marker holds the word
def starts_with(self, p):
n = self.root
for ch in p:
if ch not in n:
return False
n = n[ch]
return Trueclass TrieNode {
next = new Map<string, TrieNode>();
word: string | null = null;
}
function insert(root: TrieNode, w: string) {
let n = root;
for (const ch of w) {
if (!n.next.has(ch)) n.next.set(ch, new TrieNode());
n = n.next.get(ch)!;
}
n.word = w;
}Word Search II: trie + backtracking
Put every word in a trie, then DFS from each cell, walking the trie in step with the board. Stop as soon as the current path is not a prefix of any word.
List<String> findWords(char[][] b, String[] words) {
Trie root = new Trie();
for (String w : words) root.insert(w);
List<String> res = new ArrayList<>();
for (int r = 0; r < b.length; r++)
for (int c = 0; c < b[0].length; c++) dfs(b, r, c, root, res);
return res;
}
void dfs(char[][] b, int r, int c, Trie n, List<String> res) {
if (r < 0 || c < 0 || r >= b.length || c >= b[0].length) return;
char ch = b[r][c];
if (ch == '#' || n.next[ch - 'a'] == null) return; // not a prefix → prune
n = n.next[ch - 'a'];
if (n.word != null) { res.add(n.word); n.word = null; } // avoid duplicates
b[r][c] = '#';
dfs(b, r + 1, c, n, res); dfs(b, r - 1, c, n, res);
dfs(b, r, c + 1, n, res); dfs(b, r, c - 1, n, res);
b[r][c] = ch; // backtrack
}def find_words(board, words):
root = {}
for w in words:
n = root
for ch in w:
n = n.setdefault(ch, {})
n["$"] = w
R, C, res = len(board), len(board[0]), []
def dfs(r, c, n):
ch = board[r][c]
if ch not in n:
return
n = n[ch]
if "$" in n:
res.append(n.pop("$")) # found; remove to avoid duplicates
board[r][c] = "#"
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C:
dfs(nr, nc, n)
board[r][c] = ch
for r in range(R):
for c in range(C):
dfs(r, c, root)
return resfunction findWords(board: string[][], words: string[]): string[] {
const root = new TrieNode();
for (const w of words) insert(root, w);
const R = board.length, C = board[0].length, res: string[] = [];
const dfs = (r: number, c: number, n: TrieNode) => {
if (r < 0 || c < 0 || r >= R || c >= C) return;
const ch = board[r][c];
const nx = n.next.get(ch);
if (!nx) return;
if (nx.word) { res.push(nx.word); nx.word = null; }
board[r][c] = "#";
dfs(r + 1, c, nx); dfs(r - 1, c, nx); dfs(r, c + 1, nx); dfs(r, c - 1, nx);
board[r][c] = ch;
};
for (let r = 0; r < R; r++) for (let c = 0; c < C; c++) dfs(r, c, root);
return res;
}Binary trie: maximum XOR of two numbers
Insert each number bit by bit, from bit 31 down. For each number, walk the trie greedily choosing the opposite bit whenever it exists. That maximises the XOR from the highest bit down. O(n · 32).
int findMaximumXOR(int[] nums) {
int[][] t = new int[nums.length * 32 + 1][2];
int cnt = 1, best = 0;
for (int x : nums) {
int n = 0, m = 0, cur = 0;
for (int b = 31; b >= 0; b--) { // insert
int bit = (x >>> b) & 1;
if (t[n][bit] == 0) t[n][bit] = cnt++;
n = t[n][bit];
}
for (int b = 31; b >= 0; b--) { // query: prefer the opposite bit
int bit = (x >>> b) & 1;
if (t[m][bit ^ 1] != 0) { cur |= 1 << b; m = t[m][bit ^ 1]; }
else m = t[m][bit];
}
best = Math.max(best, cur);
}
return best;
}def find_maximum_xor(nums):
root, best = {}, 0
for x in nums:
n = root
for b in range(31, -1, -1):
n = n.setdefault((x >> b) & 1, {})
m, cur = root, 0
for b in range(31, -1, -1):
bit = (x >> b) & 1
if 1 - bit in m:
cur |= 1 << b
m = m[1 - bit]
else:
m = m[bit]
best = max(best, cur)
return bestfunction findMaximumXOR(nums: number[]): number {
type N = { [b: number]: N };
const root: N = {};
let best = 0;
for (const x of nums) {
let n = root;
for (let b = 31; b >= 0; b--) { const bit = (x >>> b) & 1; n = n[bit] ??= {}; }
let m = root, cur = 0;
for (let b = 31; b >= 0; b--) {
const bit = (x >>> b) & 1;
if (m[bit ^ 1]) { cur = (cur | (1 << b)) >>> 0; m = m[bit ^ 1]; } else m = m[bit];
}
best = Math.max(best, cur);
}
return best;
}Practice problems
- Implement Trie (Prefix Tree)medium
- Longest Common Prefixeasy
- Design Add and Search Words Data Structure'.' branches to all childrenmedium
- Replace Wordsstop at the first word endmedium
- Search Suggestions Systemmedium
- Maximum XOR of Two Numbers in an Arraybinary triemedium
- Word Search IIhard
- Palindrome Pairshard
Key takeaways
- Prefixes across many strings ⇒ trie.
- Store the whole word (or an end flag) on the terminal node.
- Trie + DFS searches many words at once and prunes dead prefixes.
- A binary trie over bits answers "maximum XOR" greedily from the top bit.
- Time O(L) per operation; memory up to total characters × alphabet size.