Tries
Prefix trees for dictionaries, autocomplete and bitwise queries.
Type "alg" into a search box and suggestions appear before you finish the word. A hash table can tell you whether "algorithm" is in its dictionary, but not which stored words begin with "alg". A trie answers both questions in time proportional to the length of what you typed, whether it holds a hundred words or a hundred million.
What you’ll learn
- Build a trie and implement insert, search, prefix counting, autocomplete and deletion, each in steps for a key of length , plus the size of any output.
- Prove the trie invariant by induction, and bound the number of nodes by the total length of the stored words.
- Choose a child representation (array, hash map, sorted list, ternary search trie) from the alphabet size and the memory budget.
- Recognize trie problems in a statement, including integers under XOR, and tell them apart from look-alikes that need a hash set or a suffix structure.
One node per prefix
A trie stores a set of strings as a rooted tree whose edges are labeled with characters. The children of a node carry distinct labels, so every node spells a unique string along the path from the root, and is a prefix of every word stored below . A flag marks the nodes where a stored word ends.
To insert a word, walk down from the root along its characters, creating each missing edge; to search, walk the same way and fail at the first missing edge. Neither operation looks at any other word, which is why the cost does not depend on how many words are stored.
How many nodes, counting the root, does the trie of the five words car, card, care, cart and cat have?
Show the answer
8
The distinct nonempty prefixes are c, ca, car, card, care, cart and cat: seven nodes, plus the root. The words have 18 characters in total, but each shared prefix is stored once, so the bound is far from tight here.
Every operation in O(L)
Two counters per node make prefix questions free: end[v] counts the stored words that end at , and cnt[v] counts the stored words that pass through , which by the invariant is the number of stored words that start with . Children live in a dictionary from character to node index.
class Trie:
def __init__(self):
self.kids = [{}] # kids[v]: character -> child node
self.end = [0] # number of stored words that end at v
self.cnt = [0] # number of stored words that pass through v
def insert(self, word):
v = 0
self.cnt[0] += 1
for ch in word:
if ch not in self.kids[v]:
self.kids[v][ch] = len(self.kids)
self.kids.append({}); self.end.append(0); self.cnt.append(0)
v = self.kids[v][ch]
self.cnt[v] += 1
self.end[v] += 1
def walk(self, s): # the node spelling s, or None
v = 0
for ch in s:
v = self.kids[v].get(ch)
if v is None:
return None
return v
def contains(self, word):
v = self.walk(word)
return v is not None and self.end[v] > 0
def count_prefix(self, p): # stored words that start with p
v = self.walk(p)
return 0 if v is None else self.cnt[v]Nodes are integers indexing parallel lists, which is faster and lighter in Python than one object per node. Inserting a word twice increments end, so the trie stores a multiset; use a flag instead if duplicates must be ignored.
def complete(t, p, k): # the first k stored words starting with p, in order
out, v = [], t.walk(p)
def dfs(u, s):
if t.end[u] and len(out) < k:
out.append(s)
for ch in sorted(t.kids[u]):
if len(out) == k:
return
dfs(t.kids[u][ch], s + ch)
if v is not None:
dfs(v, p)
return outAutocomplete is a walk to the prefix's node followed by a depth-first search below it, visiting children in alphabetical order. With the eight words above, complete(t, "t", 4) returns tea, team, ten, to.
| Operation | Cost | How |
|---|---|---|
| insert, search a word | one step per character; insert creates at most nodes | |
| count words with prefix | walk to 's node and read cnt | |
| list completions of | + the subtree explored | DFS below 's node; store the best completions in each node to get at the price of memory |
| delete (stored) | decrement cnt along the path and end at its last node; nodes whose cnt drops to 0 may be freed | |
| all words in sorted order | (number of nodes) | DFS with children in alphabetical order: this is MSD radix sort in disguise |
A trie holds words of lengths up to 20. How many nodes does count_prefix("alg") visit after the root?
- About
- At most 60, three characters times the maximum length
- 3
- Up to , one per stored word
Show the answer
C. 3
The walk follows one edge per character of the prefix and then reads the counter stored at that node: three steps, whatever the number or length of the stored words. That independence from is the point of a trie.
Memory: how a node stores its children
A trie trades memory for speed: it can need one node per stored character, so the total length of the words, not their number, sizes it. What each node costs depends on how it stores its children, and the right choice depends on the alphabet.
| Children stored as | One step | Memory per node | Use when |
|---|---|---|---|
| array of child indices | worst case | slots even in a leaf: bytes | small alphabets, contest code, maximum speed |
| hash map | expected | proportional to the children, plus a large constant | large or open alphabets: Unicode text, word tokens |
| sorted array of (character, child) | proportional to the children | static tries built once and queried often | |
| ternary search trie | a few comparisons per character | three links per node | large alphabets on a budget (Bentley & Sedgewick, 1997) |
| compressed edges (radix tree) | compares a substring per edge | at most nodes for words | long words with few branch points |
#include <string>
const int MAXN = 1000001; // total characters inserted + 1 for the root
int nxt[MAXN][26], cnt[MAXN], ends_here[MAXN], nodes = 1; // node 0 is the root
void insert(const std::string& w) {
int v = 0;
cnt[v]++;
for (char ch : w) {
int c = ch - 'a';
if (!nxt[v][c]) nxt[v][c] = nodes++; // index 0 doubles as "no child"
v = nxt[v][c];
cnt[v]++;
}
ends_here[v]++;
}
int count_prefix(const std::string& p) {
int v = 0;
for (char ch : p) {
v = nxt[v][ch - 'a'];
if (!v) return 0;
}
return cnt[v];
}The contest idiom: global arrays sized by the total input length, not by the number of words. With characters the child table alone is 104 MB, so check the memory limit first. In multi-test problems, clear only the nodes entries you used between test cases.
Recognizing it
Reach for a trie when a problem has these signals:
- many strings and questions about prefixes: "starts with", autocomplete, "how many words begin with ?";
- a dictionary consulted while a string grows one character at a time: grid word searches, segmenting a string into words, streams of characters; the trie lets you stop the moment the current string is no longer a prefix of any word;
- the longest (or shortest) stored prefix of a query: routing tables, replacing words by their roots;
- integers and XOR: a binary trie over the bits, from the most significant down.
| Problem | Key idea | Cost |
|---|---|---|
| Insert words, then answer "how many words start with ?" or list them | pass counters; DFS below 's node | , plus the output |
| Word search in a grid: which of many dictionary words can be traced through adjacent cells? | DFS from each cell while walking the trie in step; abandon a path as soon as it leaves the trie, and unmark words once found | the trie prunes every path that is not a prefix of some word |
| Replace each word of a sentence by its shortest dictionary root | walk the word down the trie and stop at the first marked node | |
| Word break: can be split into dictionary words? | DP over positions; from each reachable , walk the trie along and mark each where a word ends | trie steps |
| The maximum XOR of two numbers in an array | binary trie of the numbers, greedy descent toward the opposite bit | for -bit numbers |
For which of these problems does a trie not help?
- Suggest the stored words that complete a typed prefix
- Find the longest stored network prefix of an IP address
- Find the longest palindromic substring of a single string
- Count the stored words that start with a given string
Show the answer
C. Find the longest palindromic substring of a single string
Palindromes are about a string's symmetry around a center, not about prefixes of stored words; expanding around each center, or Manacher's algorithm (see Palindromes: Manacher's Algorithm & the Eertree), is the tool. The other three are prefix questions over a stored set: a trie's home ground.
Bitwise tries for integers
An integer below is a string of bits. Insert numbers into a binary trie from the most significant bit down, and every number becomes a root-to-leaf path of length . To find the stored that maximizes (xor), walk down from the root and at each bit take the child opposite to 's bit whenever it exists, since that sets this bit of the XOR to 1.
Greed is safe here because a bit outweighs everything below it:
| Bit | Bit of | Wanted child | Exists? | Bit of | Candidates left |
|---|---|---|---|---|---|
| 3 | 1 | 0 | yes | 1 | 1, 4, 5 |
| 2 | 0 | 1 | yes | 1 | 4, 5 |
| 1 | 0 | 1 | no: forced to 0 | 0 | 4, 5 |
| 0 | 0 | 1 | yes | 1 | 5 |
def max_xor_pair(nums, w=30): # at least two integers in [0, 2^w)
kids = [[0, 0]] # node 0 is the root; child index 0 means "none"
def insert(x):
v = 0
for b in range(w - 1, -1, -1):
bit = (x >> b) & 1
if not kids[v][bit]:
kids[v][bit] = len(kids)
kids.append([0, 0])
v = kids[v][bit]
def query(x): # max of x ^ y over the stored y
v, res = 0, 0
for b in range(w - 1, -1, -1):
want = 1 - ((x >> b) & 1)
if kids[v][want]:
res |= 1 << b
v = kids[v][want]
else:
v = kids[v][1 - want]
return res
insert(nums[0])
best = 0
for x in nums[1:]:
best = max(best, query(x)) # pair x with every earlier number
insert(x)
return besttime and at most nodes, against XORs for checking every pair. Querying each number before inserting it pairs it with all earlier ones, so every pair is considered once.
Think first The minimum XOR of two numbers in an array needs no trie: sort, and take the smallest XOR of neighbors. Why does the same trick fail for the maximum?
A small XOR needs a long common prefix of bits, and in sorted order the numbers sharing the longest prefixes with sit next to it: for , . A large XOR needs the opposite: a partner that differs from as high up as possible and then, among those, keeps differing, and such a partner can be anywhere in sorted order. The trie finds it bit by bit.
Key takeaways
- A trie has one node per distinct prefix; insert, search and prefix counting cost for a key of length , independent of the number of stored words.
- Two counters per node, words ending here and words passing through, answer "is it stored?" and "how many start with ?" and make deletion a matter of decrementing.
- Memory is the price: up to one node per stored character, times the cost of a node's child table. Choose arrays, hash maps or sorted lists by alphabet size and budget.
- Recognize it by prefixes over a set of strings, a dictionary consulted while a string grows, longest-prefix matches, and XOR over integers; text search with many patterns needs Aho–Corasick, and many queries on one text need a suffix structure.
- A binary trie answers "maximize " greedily from the top bit in , so the maximum XOR pair takes instead of .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A trie holds "car" and "care". How many new nodes does inserting "card" create, and how many does inserting "ca" create afterwards?
- 4 and 2
- 1 and 0
- 1 and 2
- 0 and 0
Show the answer
B. 1 and 0
"card" shares the path c, ca, car and needs one new node for "card". "ca" is already a path in the trie, so inserting it only marks the existing node as the end of a word.
A trie stores "tea" and "ten" but its nodes carry no end-of-word marks: search reports "found" whenever the walk succeeds. Which query does it answer wrongly?
- Searching for "tea"
- Searching for "tex"
- Counting the words that start with "te"
- Searching for "te"
Show the answer
D. Searching for "te"
The walk along "te" succeeds because "te" is a prefix of both words, so a trie without marks reports a word that was never inserted. The mark (or the counter end) is what separates stored words from mere prefixes.
Your trie stores words of length at most 10 over the 26 lowercase letters, with a 26-entry array of 4-byte indices in every node. What is the worst-case memory of the child arrays?
- About 31 MB
- About 312 MB
- About 3 MB
- About 31 GB
Show the answer
B. About 312 MB
There can be up to nodes, one per character plus the root, and each array takes bytes: about bytes, or 312 MB. That is over most contest memory limits, which is why the node count bound matters before you allocate.
In a binary trie, the maximum-XOR query takes the child opposite to 's bit at the highest level where that child exists, without looking further down. Why can this never cost the optimum?
- Because XOR is commutative and associative
- Because a 1 in bit of the result is worth , more than all lower bits together,
- Because the trie keeps the numbers in sorted order
- Because each number has a unique path, so there is only one candidate at each level
Show the answer
B. Because a 1 in bit of the result is worth , more than all lower bits together,
Numbers compare by their highest differing bit. Any partner that makes bit of the XOR 0, when another partner sharing the same higher bits makes it 1, loses whatever happens below. By induction from the top, the greedy path gives the maximum.
You build a trie over sentences, treating each word as one symbol: about distinct symbols, and most nodes have one or two children. How should a node store its children?
- An array with one slot per symbol, for worst-case steps
- A hash map, or a sorted array if the trie is static
- A linked list of all symbols
- Children are not needed: store the sentences in a hash set
Show the answer
B. A hash map, or a sorted array if the trie is static
With a huge, sparse alphabet, per-node arrays would hold mostly empty slots in every node. A hash map stores only the children that exist, with expected steps; a sorted array is even leaner when no insertions follow, at per step.
Go deeper
- Aho–Corasick: Matching a Whole Dictionary · A trie with failure links scans the text once for every pattern.
- Compressed Tries: Radix Trees & Patricia · Collapsing chains of single children, from IP routing to suffix trees.
- Binary Tries & Maximum XOR · Bitwise tries for maximum-XOR pairs, subarrays and queries.
Further reading
- E. Fredkin, "Trie memory," Communications of the ACM 3(9) (1960), 490–499.
- R. de la Briandais, "File searching using variable length keys," Proceedings of the Western Joint Computer Conference (1959), 295–298.
- R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 5.2 (tries and ternary search tries).
- D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.3 (digital searching).