Learn the pattern · ~15 min
Trie (Prefix Tree)
also called prefix tree, radix tree (compressed)
Store words as paths of letters from one root, so words that share a prefix share the path, and every lookup costs only the length of the query, not the number of words.
Reach for it when you read
- +Many words, many queries about prefixes: "does any word start with…", autocomplete, shortest or longest prefix.
- +Match a whole dictionary against a text or a grid at once (word search over a board, splitting a string into dictionary words).
- +Search with wildcards like
.that match any letter. - +Maximum or minimum XOR of a number with any number from a set: a binary trie over the bits.
Not this one when
- ×Exact lookups only, never prefixes: a hash set is simpler and as fast.
- ×One pattern inside one long text: string matching (KMP, Z, rolling hash), not a trie.
- ×Prefixes of a sorted word list with few queries: sort and binary search the prefix range.
Learn Trie (Prefix Tree)
First, what are a "prefix" and a "trie"?
A prefix of a word is any start of it. The prefixes of cat are c, ca and cat. at is not one: it doesn't start at the beginning.
A trie (said "try", from retrieval) stores words as paths of letters going down from one root node. Each edge is a letter, so each node stands for the prefix spelled on the way to it. Words that start the same way share the start of their path.
How do words go in?
Insert ca, cat, do, bat, in that order. The rule:
Walk down from the root one letter at a time. If the child for the next letter is missing, create it. At the last letter, mark the node as the end of a word.
| insert | what happens | new nodes | nodes in total (with root) |
|---|---|---|---|
| ca | nothing exists yet: create c, then a; mark a |
2 | 3 |
| cat | c and a exist, walk through them; create only t, mark it |
1 | 4 |
| do | no d under the root: create d, then o; mark o |
2 | 6 |
| bat | no b: create b, a, t; mark t |
3 | 9 |
Here is the result, with * on the nodes where a word ends:
root
/ / \
b c d
\ \ \
a a* o*
\ \
t* t*cat cost one new node, because ca was already there. The more words share their starts, the more the trie saves.
The code for it
struct Node {
Node* next[26] = {}; // one slot per letter, null = no such child
bool isEnd = false; // a word ends exactly here
int count = 0; // words that pass through here (used later)
};
Node* root = new Node();
void insert(const string& w) {
Node* cur = root;
for (char ch : w) {
int c = ch - 'a';
if (!cur->next[c]) cur->next[c] = new Node(); // create only what's missing
cur = cur->next[c];
cur->count++;
}
cur->isEnd = true;
}You don't need to memorise this. It's the table above: walk, create what's missing, mark the end. (The count line counts how many words pass through each node; it comes back later.)
Why the isEnd flag, if the path is already there? Because a path is not a word. The node c exists, but c was never inserted: it's only on the way to ca. Without the flag you couldn't tell ca (inserted) from c (not).
Fine, but how does this help us?
Here's a classic problem, Replace Words. You get a list of roots, ca, cat, do, bat, and a sentence, cattle dot cab bath dig. Replace every word that starts with a root by the shortest such root. A word with no root stays as it is.
By hand:
| word | roots that are a prefix of it | shortest | becomes |
|---|---|---|---|
| cattle | ca, cat | ca | ca |
| dot | do | do | do |
| cab | ca | ca | ca |
| bath | bat | bat | bat |
| dig | none | none | dig |
So the answer is ca do ca bat dig.
The brute force
For each word, test every root: is it a prefix, and is it shorter than the best so far?
string shortestRootBrute(const string& w, const vector<string>& roots) {
string best = w;
for (const string& r : roots) // try every root
if (r.size() < best.size() && w.compare(0, r.size(), r) == 0)
best = r; // a shorter root that fits
return best;
}It gives ca do ca bat dig. At LeetCode's sizes (up to 1,000 roots, a sentence of 10⁶ characters) this passes: 10⁵ words × 1,000 roots is 10⁸ checks, about 0.2 s with -O2, because a failed check stops at the first different letter. It breaks when both lists grow: 10⁵ words against 10⁵ roots is 10¹⁰ checks, 18 seconds. Time limit exceeded.
The one thought that fixes it
Stop at the word cattle. The brute force compares it with all four roots, including do and bat, which don't even start with c.
Now walk cattle down the trie instead: c, then a, then t. Every root that is a prefix of cattle must spell the start of cattle, so it ends on this one path. ca ends at the second node, cat at the third. Roots like do and bat sit on other branches and are never looked at.
And along the path the roots come shortest first. So the first end mark you meet is the answer: at a you see * and stop with ca, without even reaching cat. If a letter has no child, no root can fit and the word stays as it is.
string shortestRoot(const string& w) {
Node* cur = root;
for (int k = 0; k < (int)w.size(); k++) {
cur = cur->next[w[k] - 'a'];
if (!cur) return w; // no root is a prefix of w
if (cur->isEnd) return w.substr(0, k + 1); // the first end met is the shortest root
}
return w;
}Dry run
Same trie, same sentence:
| word | walked | stopped because | becomes |
|---|---|---|---|
| cattle | c, a | end mark at ca |
ca |
| dot | d, o | end mark at do |
do |
| cab | c, a | end mark at ca |
ca |
| bath | b, a, t | end mark at bat |
bat |
| dig | d | d has no i child |
dig |
ca do ca bat dig, the same answer as the brute force.
Why it's fast
Count what happens to each letter. Building the trie costs one step per letter of the roots. Each word then walks at most one step per letter, and often far fewer (cattle stops after 2). So the whole sentence costs at most its total number of letters: about 10⁶ steps for 10⁵ words of 10 letters, instead of 10⁸ checks.
Memory is one node per distinct prefix, and each node here holds 26 pointers. For a big alphabet, use a map per node instead of an array.
From "every word against every root" to "every word walks one path", because all the roots that could match lie on that path.
Search and startsWith? Same walk, different question
That's Implement Trie. Both follow the letters down. search asks "does a word end here?", startsWith only asks "does the path exist?":
Node* walk(const string& s) { // follow s from the root; null if the path breaks
Node* cur = root;
for (char ch : s) {
cur = cur->next[ch - 'a'];
if (!cur) return nullptr;
}
return cur;
}
bool search(const string& w) { Node* n = walk(w); return n && n->isEnd; } // a word ends here
bool startsWith(const string& p) { return walk(p) != nullptr; } // the path exists| call | the walk | answer |
|---|---|---|
search("ca") |
reaches a, which is marked |
true |
search("c") |
reaches c, not marked |
false |
startsWith("c") |
the path exists | true |
search("cab") |
a has no b child |
false |
startsWith("ba") |
the path exists | true |
How many words start with a prefix? Read the count
That's the count field in the node: insert adds 1 to every node it passes. So the answer is the count at the prefix's last node. walk("ca")->count is 2 (ca and cat), and so is walk("c")->count.
A wildcard? Try every child
Now . matches any one letter. At a normal letter, follow one child. At a ., try all of them:
bool match(Node* cur, const string& w, int k) {
if (!cur) return false;
if (k == (int)w.size()) return cur->isEnd;
if (w[k] != '.') return match(cur->next[w[k] - 'a'], w, k + 1);
for (Node* child : cur->next) // '.': try every child
if (match(child, w, k + 1)) return true;
return false;
}d. → true (do), .at → true (cat or bat), b. → false: ba is a path, but no word ends there.
Remember this
- Many words and many questions about prefixes ("starts with", "shortest root", autocomplete): build a trie once, then each question costs its own length.
- A path is not a word: mark the node where a word ends (
isEnd, or a count). - Need a number per prefix (how many words, the top 3 suggestions)? Store it in the node while inserting.
- For numbers and XOR, make a binary trie of the bits, highest bit first.
- Whenever a problem puts many strings against many prefix questions, it's a trie.
Practise it on Implement Trie (Prefix Tree), then Replace Words, Search Suggestions System (answers stored in the nodes), Design Add and Search Words Data Structure (the wildcard), Maximum XOR of Two Numbers in an Array (a binary trie) and Word Search II (the trie steers a grid search).
Below, watch Implement Trie (Prefix Tree) run line by line.
Watch it work, line by line
Implement Trie (Prefix Tree) ↗, insert cat, car, card, dog; search car, search ca, startsWith ca, search cow → true, false, true, false. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Do I have many words (or numbers as bits) and keep asking about their prefixes, letter by letter from the start?
Reach for it when
- +many words with prefix queries
- +autocomplete
- +dictionary-driven search on a grid
- +maximise XOR (binary trie)
- +total characters up to ~1e6
It fails 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
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why does a trie need
isEndwhen the path already exists?RevealA path can exist only because a longer word passes through it. "ca" exists for "cat" but isn't a word.
2What does
searchcost with a million stored words?RevealO(length of the query). The number of stored words doesn't matter.
3In a binary trie for max XOR, which child do you prefer at each bit?Reveal
The opposite bit to the current number's bit, if that child exists. A 1 high up beats everything below it.
Practice ladder
- 1Implement Trie (Prefix Tree)the hookMedium
- 2Replace Wordsstop at the first endMedium
- 3Search Suggestions Systemanswers stored in nodesMedium
- 4Design Add and Search Words Data StructurewildcardsMedium
- 5Maximum XOR of Two Numbers in an Arraybinary trieMedium
- 6Word Combinationstrie plus DPMedium
- 7Word Search IItrie guides a grid searchHard
- 8Maximum XOR With an Element From Arraybinary trie, offlineHard
- 9Maximum Genetic Difference Querybinary trie with deletes, on a treeHard
Finished Trie (Prefix Tree)? Mark it done and Lessgo moves you to the next step.