A trie (prefix tree) stores strings by sharing their common prefixes. The root represents the empty string; each edge adds one character; walking root-to-node spells that node's prefix. A boolean flag marks nodes where a stored word ends. Insert "cat", "car", and "cart" and they share the c-a-r spine, branching only where they must, the structure is literally the vocabulary it holds.
Every operation costs O(L) where L is the word length, independent of how many words are stored. That is the trie's superpower: search a dictionary of a million words in the time it takes to spell one. A hash map also does O(L) exact lookups (hashing the string touches every character), but it cannot answer "which stored words start with 'car'?" without scanning everything. A trie answers by walking to the 'car' node and enumerating its subtree, the prefix query is native.
A minimal, complete trie
class TrieNode {
children = new Map(); // char → TrieNode
isWord = false;
}
class Trie {
root = new TrieNode();
insert(word) { // O(L)
let node = this.root;
for (const ch of word) {
if (!node.children.has(ch)) node.children.set(ch, new TrieNode());
node = node.children.get(ch);
}
node.isWord = true;
}
search(word) { // O(L), exact match
const node = this.walk(word);
return node !== null && node.isWord;
}
startsWith(prefix) { // O(L), prefix query, hash maps can't do this
return this.walk(prefix) !== null;
}
walk(s) {
let node = this.root;
for (const ch of s) {
node = node.children.get(ch);
if (!node) return null;
}
return node;
}
}Cost summary
| Operation / case | Cost | Notes |
|---|---|---|
| Insert / search / startsWith | O(L) | L = word length, independent of dictionary size |
| Enumerate prefix matches | O(L + matches) | walk to prefix, DFS the subtree |
| Space | O(total characters) | prefix sharing shrinks it in practice; compressed tries (radix trees) shrink it further |
Alphabet size affects the constant: 26 letters, but Map/HashMap children make Unicode natural at a small pointer cost.
Practice
A trie contains "car", "cat", "cart". How many nodes does the path for the prefix "car" visit, including the root?
Reveal explanation
Root (empty), then c, a, r, 4 nodes. The 't' of cat and 't' of cart branch only after the shared c-a-r spine.