A tree where each step is one letter, so finding every word that starts with 'ca' is instant. The heart of autocomplete.
A trie (say "try", also called a prefix tree) is a tree where each step down is one letter. Words that share a beginning share a path. To find every word that starts with "ca", you walk c, then a, and everything below is your answer.
A hash map answers "is this exact word here?" very well. It cannot answer "what words start with ca?" without checking every key. A trie is built for exactly that second question, because its shape is the prefixes.
Each node holds a letter (really, the edge into it does), links to its children, and a flag saying "a word ends here". The root is empty. The word "car" is the path root → c → a → r, with the flag set on r. The words "card", "care" and "cart" reuse that path and add one more letter each.
For autocomplete, the walk is only half the work. Below the prefix there may be millions of words, and you want the best few. The classic trick is to store the top K suggestions on every node, built ahead of time from search counts. Then a request is: walk L letters, read K words. No search below the node at all.
| Operation | How it works | Cost |
|---|---|---|
| Insert word | Walk letters, create missing nodes, set the end flag | O(L) |
| Search exact word | Walk letters, check the end flag | O(L) |
| Starts-with | Walk the prefix letters, just check the path exists | O(L) |
| List all with prefix | Walk the prefix, then visit the whole subtree | O(L + size of subtree) |
| Top-K with prefix | Walk the prefix, read the list cached on the node | O(L + K) |
| Delete | Clear the flag, then remove nodes that are now unused | O(L) |
| Type | Idea | Good for | Watch out |
|---|---|---|---|
| Plain trie | One node per letter | Learning, small sets | Lots of memory |
| Compressed (radix / Patricia) trie | Merge a chain of single-child nodes into one edge with a string | Large word lists, routers | Splitting edges on insert is fiddly |
| Ternary search tree | Each node has three links (less, equal, more) | Saves space on wide alphabets | A bit slower than a trie |
| Double-array / FST | Packed arrays or automata | Search engine term dictionaries | Hard to update, build offline |
A small fixed word list with search counts. Real autocomplete keeps a few million entries, stores the cached list on each node as short IDs, and rebuilds it offline from search logs.
class Node {
kids = new Map<string, Node>();
end = false;
top: string[] = []; // cached top-K for autocomplete
}
function insert(root: Node, word: string) {
let n = root;
for (const ch of word) {
if (!n.kids.has(ch)) n.kids.set(ch, new Node());
n = n.kids.get(ch)!;
}
n.end = true;
}
function startsWith(root: Node, prefix: string): Node | null {
let n: Node | undefined = root;
for (const ch of prefix) { n = n.kids.get(ch); if (!n) return null; }
return n; // read n.top for suggestions
}| Term | Meaning in easy words |
|---|---|
| Trie / prefix tree | A tree where each edge is a letter and paths spell words |
| Prefix | The first few letters of a word |
| Root | The empty top node |
| End-of-word flag | A mark saying a full word finishes at this node |
| Radix (Patricia) trie | A trie where chains of single-child nodes are merged into one edge |
| Ternary search tree | A trie variant with three links per node (less, equal, more) |
| Top-K cache | The best K words stored on each node for instant suggestions |
| Typeahead | Suggestions that appear as the user types |
| Debounce | Wait for a short pause in typing before sending a request |
| Longest-prefix match | Finding the longest stored prefix of an input, as routers do |
| FST | Finite state transducer, a very compact trie-like structure used in Lucene |
| Choice | We gain | We lose |
|---|---|---|
| Trie vs hash map | Prefix queries | Memory and plain exact-lookup speed |
| Cache top-K per node | Constant-time suggestions | Space and rebuild work |
| Radix compression | Far fewer nodes | More complex inserts |
| Child array vs map | Array: fast. Map: small | Array wastes space on sparse nodes |
| Offline rebuild | Simple and stable | Suggestions lag behind trends |
| Shard by prefix | Spreads data and load | Hot prefixes need extra splits |