Tries · Lesson
Tries, explained: prefix trees for words, autocomplete and XOR
Learn the trie (prefix tree): insert, search and starts-with, autocomplete, word search on a grid and the bitwise trie, with code in Java, Python, C++ and JS.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
What a trie is
A trie (say "try", also called a prefix tree) stores words one character per level. The root is the empty string, each edge adds one letter, and words that share a prefix share the same path: "car", "cart" and "care" all walk through c → a → r.
Each node also needs a flag: does a word end here? Without it you cannot tell the word "car" from the prefix of "cart". Looking up a word or a prefix of length L takes L steps, no matter how many words the trie holds.
When a trie beats a hash set
A hash set answers "is this exact word here?" just as fast. A trie wins when the question is about prefixes:
- Starts-with queries: every word below a node shares its prefix, so autocomplete is a walk plus a small DFS.
- Searching many words at once: walking a grid or a string, you can stop the moment no word continues the current path.
- Wildcards: a
.that matches any letter just tries every child at that level. - Bits instead of letters: store numbers bit by bit, highest first, and you can find the number with the largest XOR greedily.
What it costs
| Operation | Time | Space |
|---|---|---|
| Insert a word of length L | O(L) | O(L) new nodes at most |
| Search a word or check a prefix | O(L) | O(1) |
| Build from words with N letters in total | O(N) | O(N · alphabet) with child arrays |
| Max XOR of a number with a bitwise trie | O(B) for B bits | O(n · B) for n numbers |
| Same prefix queries on a sorted list (binary search) | O(L log n) | O(1) extra |
Built into your language
// no trie in the standard library: write a node with 26 children (or a HashMap)
"apple".startsWith("app"); // true
// a sorted set can answer prefix questions too
TreeSet<String> words = new TreeSet<>(List.of("app", "apple", "bat"));
words.ceiling("ap"); // "app": the first word >= the prefix
words.subSet("ap", "ap" + Character.MAX_VALUE); // [app, apple]: every word with the prefix # no trie in the standard library: a dict of dicts (or a node class) is common
"apple".startswith("app") # True
from bisect import bisect_left
words = sorted(["bat", "apple", "app"])
i = bisect_left(words, "ap") # 0: the first word >= the prefix; scan while it starts with "ap"
import os
os.path.commonprefix(["flower", "flow", "flight"]) # "fl" // no trie in the standard library: write a node with 26 child pointers
string w = "apple";
w.compare(0, 3, "app") == 0; // true: w starts with "app" (C++20 also has w.starts_with("app"))
set<string> words = {"app", "apple", "bat"};
auto it = words.lower_bound("ap"); // "app": the first word >= the prefix; walk on while it matches // no trie built in: use nested objects or a Map per node
"apple".startsWith("app"); // true
const root = new Map(); // one node: letter -> child node
root.set("a", new Map());
root.has("a"); // true
const words = ["bat", "apple", "app"].sort(); // ["app", "apple", "bat"] (string sort is fine) Mistakes everyone makes
- Confusing "the prefix exists" with "the word exists":
searchmust check the end flag. - Using a fixed 26-child array when the input has uppercase letters, digits or
/: use a map. - Forgetting to decrement counts on erase, so prefix counts drift.
- Building a new string at every step of a DFS: pass the node along, or store the whole word in its end node.
The 3 patterns, in order
Each one: the idea and template, its variations with a worked example, then problems for you to solve.
- 1 Trie basics: insert, search, prefixes and autocomplete Walk the word letter by letter, creating missing children on insert and stopping at a missing child on search. Counts in the nodes, wildcards and autocomplete are small additions to the same walk. 4 variations · 7 problems
- 2 Trie + backtracking: find many words at once Put all the words in a trie, then backtrack over the grid while walking the trie at the same time. The moment the current path is not a prefix of any word, stop: that pruning is what makes it fast. 1 variation · 1 problem
- 3 Bitwise trie: the largest XOR, bit by bit Store each number as a path of bits from the highest to the lowest, so every node has at most two children. To get the largest XOR with x, walk down and take the opposite bit whenever it exists. 1 variation · 1 problem