Tries (Prefix Trees)
A tree keyed by characters — O(L) insert and lookup, and instant prefix queries for autocomplete and dictionaries.
A trie (pronounced "try", from retrieval) stores a set of strings as a tree where each edge is a character. Words that share a prefix share a path. Lookup cost depends only on the word length L, not on how many words are stored.
Operations
| Operation | Time | Notes |
|---|---|---|
| Insert word | O(L) | Create missing nodes along the path |
| Search word | O(L) | Path must exist and end at an end-of-word node |
| Starts-with prefix | O(P) | Path just has to exist |
| List all words with a prefix | O(P + output) | DFS below the prefix node |
Compared with a hash set, a trie answers prefix questions natively and lists keys in sorted order, at the cost of more memory.
class Trie {
private static class Node {
Node[] next = new Node[26]; // or Map<Character, Node> for large alphabets
boolean end;
}
private final Node root = new Node();
public void insert(String word) {
Node n = root;
for (char c : word.toCharArray()) {
int i = c - 'a';
if (n.next[i] == null) n.next[i] = new Node();
n = n.next[i];
}
n.end = true;
}
public boolean search(String word) {
Node n = walk(word);
return n != null && n.end;
}
public boolean startsWith(String prefix) {
return walk(prefix) != null;
}
private Node walk(String s) {
Node n = root;
for (char c : s.toCharArray()) {
n = n.next[c - 'a'];
if (n == null) return null;
}
return n;
}
}class TrieNode:
__slots__ = ("children", "end")
def __init__(self):
self.children = {}
self.end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
n = self.root
for c in word:
n = n.children.setdefault(c, TrieNode())
n.end = True
def _walk(self, s: str):
n = self.root
for c in s:
n = n.children.get(c)
if n is None:
return None
return n
def search(self, word: str) -> bool:
n = self._walk(word)
return n is not None and n.end
def starts_with(self, prefix: str) -> bool:
return self._walk(prefix) is not Noneclass TrieNode {
children = new Map<string, TrieNode>();
end = false;
}
class Trie {
private root = new TrieNode();
insert(word: string) {
let n = this.root;
for (const c of word) {
if (!n.children.has(c)) n.children.set(c, new TrieNode());
n = n.children.get(c)!;
}
n.end = true;
}
private walk(s: string): TrieNode | null {
let n: TrieNode | undefined = this.root;
for (const c of s) {
n = n.children.get(c);
if (!n) return null;
}
return n;
}
search(word: string) { return this.walk(word)?.end ?? false; }
startsWith(prefix: string) { return this.walk(prefix) !== null; }
}Memory trade-offs
- Array children (
Node[26]): fastest, but every node reserves 26 pointers even if it uses one. - Map children: compact for sparse or large alphabets (Unicode), slightly slower.
- Radix / Patricia tree: compresses chains of single-child nodes into one edge labelled with a whole substring. Used in IP routing tables, Linux's page cache, and Ethereum's state tree.
Where tries are used
- Autocomplete and spell checking — walk to the prefix, DFS for suggestions (often ranked by frequency stored in nodes).
- IP routing — longest-prefix match over binary address bits.
- Word games / Boggle / Word Search II — prune grid DFS the moment a path is not a prefix of any word.
- XOR maximisation — a binary trie over bits finds the number maximising
x XOR yin O(32). See Bitwise XOR.
- A trie stores strings as paths of characters; shared prefixes share nodes.
- Insert, search and prefix queries cost O(length), independent of the number of words.
- Mark word ends explicitly — a prefix is not a word.
- Radix trees compress single-child chains to save memory.
QImplement autocomplete returning the top 3 suggestions for each typed prefix.medium
Build a trie; at each node store the top-3 words (by frequency or lexicographically) passing through it, updated on insert. Each keystroke moves one node down and returns the stored list in O(1). Alternatively, sort the words and binary-search the prefix range.
QTrie vs hash set for a dictionary — when is a trie better?easy
When you need prefix queries, sorted iteration, or longest-prefix matching. A hash set is simpler and usually faster for exact membership only.