A trie (also called a prefix tree, pronounced "try") is a tree that stores words. Each step down the tree is one letter, so a word is a path from the root. Words that start the same way share the same path for their common beginning.
What it looks like
The words car, card, care and cat:
c and a are stored only once, even though four words use them.
What a node holds
class TrieNode {
children = new Map() // letter → next node
isEnd = false // does a whole word end here?
}children: where you can go next, one entry per letter.isEnd: marks the end of a word. Without it, you couldn't tell the wordcarfrom the prefixcaon the way tocat.
The one move: walk the letters
Every trie operation is the same loop: start at the root and follow one letter at a time.
let node = root
for (const char of word) {
node = node.children.get(char)
if (!node) break // no stored word continues this way
}| Operation | During the walk | At the end |
|---|---|---|
| insert a word | create any missing child | set isEnd = true |
| search a word | missing letter → false | return isEnd |
| startsWith a prefix | missing letter → false | return true |
Why bother? Speed that ignores the dictionary's size
With L = the length of the word you're looking up:
| Question | List of words | Hash set | Trie |
|---|---|---|---|
| Is this exact word stored? | O(n · L) | O(L) | O(L) |
| Does any word start with this prefix? | O(n · L) | O(n · L) | O(L) |
A hash set is great for exact words, but useless for prefixes. A trie answers prefix questions in time that depends only on the prefix length, whether you've stored 10 words or 10 million.
The real superpower: pruning a search
When you're exploring letter by letter (a grid, wildcards, a sentence), the trie tells you at every step: "does any word still start like this?" If not, you stop exploring that branch immediately.
- Design Add and Search Words: a
.wildcard tries every child, but real letters follow one path. - Word Search II: a DFS on the board moves through the trie at the same time and abandons paths no word could follow.
How to recognize this category
- The problem has a dictionary of words and asks about prefixes, autocomplete, or "starts with".
- You're searching for many words at once (in a grid, a string or a stream).
- Matching with wildcards, letter by letter.
Common mistakes
- Forgetting
isEnd, so a prefix is reported as a word. - Treating "the path exists" as "the word exists". That's
startsWith, notsearch. - Not pruning. If you walk the trie but don't stop when a child is missing, you lose the whole benefit.