Tries: one node per prefix
1 A keyboard that finishes words
A phone keyboard suggests words while we type. After "ca", it offers car, cart, care and cat.
A hash set of words answers "is car a word?" in about one step. But a hash only knows whole words. To answer "which words start with ca?", the set has to check every word. With 10⁵ words and 10⁵ such questions, that is around 10¹⁰ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
The words themselves show the way out. Car, cart, care and cat all start with "ca". We can store that start once and keep every word that begins with it below. Then the keyboard only has to find "ca" and look underneath.
2 One node per prefix
A trie (said "try") stores words that way. It is a tree, as in the tree lessons, but a node can have up to 26 children, one for each letter. Each node stands for one prefix: the first few letters of a word. The root is the empty prefix. Each edge adds one letter, so the path from the root to a node spells its prefix.
Here is the trie of car, cat, cart, care and dog:
Words that start the same share a path. The five words have 17 letters, but the trie has only 9 nodes below the root. Typing on the keyboard is a walk down this tree: each key moves one node down.
The path alone cannot tell a word from a prefix. "car" is a word and "ca" is not, but both are nodes on the way to "cart". So each node keeps one more field, the end flag. It is true when a word ends exactly at that node, and the drawing rings those nodes.
In code, a node holds 26 child slots and the flag. The slot for a letter c is at index c - 'a', so a is slot 0 and z is slot 25. An empty slot means no word continues with that letter:
3 Insert: walk, and make what is missing
To insert a word, we start at the root and follow its letters. For each letter, we move to the child for that letter, and make that child first if it is missing. After the last letter, we set the end flag on the node we stand on.
Here are the five words going in, one at a time. The blue path is the word just inserted:
Step 4, inserting care, shows both cases:
| Letter | Child there? | What insert does | Node after |
|---|---|---|---|
| c | yes | move down | c |
| a | yes | move down | ca |
| r | yes | move down | car |
| e | no | make it, move down | care |
| end | set the end flag | care, ringed |
Only e is new. The first three nodes were built by the words before it.
4 Search and startsWith
The problem "Implement Trie (Prefix Tree)" asks for three methods: insert, search and startsWith.
search(word)asks whether the word was inserted.startsWith(prefix)asks whether any inserted word starts with the prefix.
Both walk down the same way insert does, but they never make a node. A missing child means the answer is false. The two differ only at the end. search needs the end flag, and startsWith only needs the node.
Steps 3 and 4 stop at the same node. Only the ring tells the two answers apart.
The empty prefix is the start of every word. The walk takes no steps, ends on the root, and startsWith("") is true.
Since search and startsWith walk the same way, one helper, findNode, does the walk for both. It returns the node for a prefix, or null when the walk falls off the tree:
After inserting our five words, every tab gives true for search("car"), startsWith("ca") and startsWith(""), and false for search("ca"), search("cab") and startsWith("dot").
C++
Write = {} on the array. It sets all 26 pointers to null. Without it, the slots hold leftover memory, and the null check follows a pointer to nowhere.
The array starts full of null. new TrieNode[26] needs no loop to clear it. A char minus 'a' is already an int, so it works as an index.
A dict works too. Many Python solutions use children = {} keyed by the letter. It skips the ord arithmetic and stores only the children that exist.
Letters are not numbers. charCodeAt(0) gives a letter's code, so subtracting the code of "a" turns a into 0. A Map keyed by the letter is the other common choice.
Loop over bytes. word[i] is a byte, so word[i] - 'a' is a slot from 0 to 25. The array lives inside the struct, so &TrieNode{} starts with all 26 slots nil.
Option<Box<TrieNode>> per slot. A child is None or a box that owns it. get_or_insert_with makes the child only when it is missing, and as_deref()? returns None from find_node at the first missing child.
The array starts full of null. new TrieNode[26] needs no loop to clear it. A char minus 'a' is already an int, so it works as an index.
5 Cost, and array against map
Each method moves one node per letter. So insert, search and startsWith take O(L) time for a word of length L, however many words the trie holds. Back on the keyboard, 10⁵ questions of about 10 letters each take around 10⁶ steps instead of 10¹⁰.
Memory is the price. Every node carries 26 slots, used or not. Take 10⁵ words of 10 letters each:
- Nodes. At most one per letter, so 10⁶ nodes. Shared prefixes only lower this.
- Slots. 26 per node, so 2.6 × 10⁷.
- Bytes. At 8 bytes a pointer, about 200 MB.
Random words share little beyond their first few letters, so a test can come close to this. In general, the space is O(N × 26) for N letters inserted.
A map in each node stores only the children that exist:
| Array of 26 | Map | |
|---|---|---|
| Find a child | one index | one hash lookup, slower |
| Memory | 26 slots per node, mostly empty | one entry per real child |
| Letters | a small, known set | any characters |
For lowercase letters, the array is the usual choice. A map fits when the alphabet is large or unknown, or when 26 slots per node would not fit in memory.
6 Counts, deletes and wildcards
The keyboard could also show how many words start with what we typed. For that, each node keeps a prefix count: how many inserted words pass through it. Insert adds 1 at every node it walks through, so the count for "ca" is one walk and one read.
| Prefix | Words through it | Count |
|---|---|---|
| ca | car, cat, cart, care | 4 |
| car | car, cart, care | 3 |
| cat | cat | 1 |
| do | dog | 1 |
A second count in place of the end flag says how many times the word itself was inserted. "Implement Trie II (Prefix Tree)" asks for both counts.
Two more operations build on the same walk:
- Deleting a word. Clearing the end flag is not enough. After deleting dog, the nodes d and o remain, and
startsWith("do")still says true. Either remove the nodes no other word uses, going back up from the end, or take 1 from the prefix count along the path and treat a node with count 0 as missing. - A wildcard letter. In "Design Add and Search Words Data Structure", a
.matches any letter. At a., the walk tries every child, and the search is true if any branch ends on a ring. This is a depth-first search, written with recursion. For "ca.", it tries r and t, and car is ringed.
7 Mistakes and edge cases
- No end flag. Without it,
searchreturns true for any prefix. After inserting car,search("ca")comes out true instead of false. - Setting the flag only on a new node. Insert cart, then car. Inserting car makes no node, so its flag is never set, and
search("car")returns false. - A search that makes nodes. Copying insert's loop into
searchmakes a node for every missing letter. Aftersearch("cab")returns false,startsWith("cab")returns true. - Assuming lowercase letters.
c - 'a'is a slot from 0 to 25 only for a to z. An uppercase C gives −30, outside the array, which is a Runtime Error. Read the constraints for the alphabet, and use 128 slots or a map for anything wider. - Treating the empty prefix as a miss. Every word starts with the empty prefix, so
startsWith("")is true. The loop already returns the root for it. An extraifthat returns false breaks it.
8 When to use a trie
The sign is many words and questions about how they start, or a walk that matches words one letter at a time.
- Prefix questions over many words. Autocomplete, or counting words that start with something. Build the trie once, then each question is one walk.
- Words built one letter at a time. A word can be built that way exactly when every node on its path is ringed. "Longest Word in Dictionary" and "Longest Word With All Prefixes" check this.
- Matching many words during one walk. In "Word Search II", the walk over the grid moves down the trie at each cell. It stops as soon as no word starts with the letters so far.
- All substrings of one string. Every substring is a prefix of some suffix, so a trie of the suffixes holds every substring.
- Not for whole words alone. When every question is "is this exact word there?", a hash set is simpler.
The next lesson stores numbers in a trie, one bit per level, to find the pair with the largest XOR.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.