Trie
A tree where each edge is one character, so the path from the root to a node spells a prefix and every word below that node starts with it. It exists because "all words starting with sys" is one walk of three nodes, not a scan of the dictionary.
What it costs
| Operation | Cost | Note |
|---|---|---|
| Prefix lookup | O(p) | p is the prefix length. Walk one node per character; the subtree below is every completion. |
| Top-k completions | O(p + k) | Only if each node caches its k best completions; otherwise a subtree walk that can be huge for short prefixes. |
| Insert | O(L) | L is the word length. Create nodes that do not exist yet, then update cached top-k along the path. |
| Delete | O(L) | Unmark the terminal node; prune nodes with no children; recompute cached lists on the path. |
Memory: One node per distinct prefix. 10 million hashtags of average length 12 share prefixes heavily, giving about 30 million nodes; at roughly 40 bytes per node plus a cached top-10 list on the hot upper nodes, about 1.5 GB in a plain implementation, a third of that as a compressed (radix) trie.
Prefix "sys" is one path; every completion hangs below it
Each edge is a character. The node reached by s → y → s roots every word starting with sys, and it caches its top completions so the query never walks the subtree.
How it works
- The root is an empty prefix. Each node holds a map from character to child node, a flag saying whether the path so far is a complete word, and optionally a weight (how popular that word is).
- To insert "system", start at the root, follow or create the child for s, then y, s, t, e, m, and mark the last node as a word with its weight.
- To look up the prefix "sys", follow three edges. The node you land on is the root of every word that starts with sys; "system", "sysadmin" and "sysdesign" are all below it.
- To answer "top 10 completions for sys" quickly, each node stores its own top-10 list of (word, weight), computed from its children. The query is then a walk of three nodes and one list read, with no subtree traversal.
- When a word's weight changes (a hashtag trends), walk its path from the leaf up to the root and re-merge the top-10 list at each node, which is L nodes of work.
- A radix trie compresses chains of single-child nodes into one edge labelled with the whole substring ("ystem" instead of y, s, t, e, m), cutting node count several-fold for long tails.
Why it is shaped this way
- Prefix sharing is the whole point: every word starting with "sys" is reachable from one node, so the structure is the index and the result set at once.
- Caching top-k at each node trades memory (one short list per node) for a bounded query cost, which is what makes a sub-10-millisecond suggestion box possible.
Worked example
Hashtag autocomplete for the news feed
- 10M distinct hashtags; the top 1M carry 99% of searches. Build the trie over the top 1M with a weight of uses in the last 7 days; refresh nightly and patch trending tags hourly.
- A user types "#sy". Walk two nodes, read the cached top-10 at the "sy" node: [#sydney 410K, #system 220K, #syria 180K, ...]. One memory walk, under 50 microseconds; the HTTP round trip dominates.
- Node count: 1M tags of average 11 characters would be 11M nodes without sharing; with sharing about 3.5M. At 40 bytes each plus top-10 lists of 10 × 16 bytes on the 400K nodes with two or more children, roughly 140 MB + 64 MB ≈ 200 MB. Fits on every API server, so no network call per keystroke.
- A tag trends: #systemdesign jumps from 2K to 300K uses. Walk its 13 nodes from leaf to root and re-merge each top-10. 13 small merges, microseconds. The suggestion for "#sy" updates in the next hourly patch.
- Serving: 50K keystrokes per second across the fleet, each a local lookup. No shared store on the hot path; the nightly build is shipped as a file.
When it is the wrong choice
- Fuzzy or typo-tolerant matching: a trie only follows exact characters. Use an n-gram index or a search engine's completion suggester instead.
- Suggestions that depend on the user (personalised ranking): the cached top-k is global. Fetch a larger candidate list from the trie and re-rank per user.
- Very long or very numerous strings with little shared prefix (URLs, UUIDs): node count approaches total characters and a sorted array with binary search is smaller and nearly as fast.
Interviewer follow-ups
Answer out loud before you open each one.
How do you return the top 10 completions without walking the whole subtree?
Store a top-10 list at every node, built bottom-up from its children when the trie is constructed. The query becomes walk-the-prefix plus read-one-list. The cost is memory for the lists and L merges whenever a weight changes.
How much memory does a trie over a million terms take, and how do you shrink it?
Roughly node count times 30 to 50 bytes; a million 11-character terms share enough prefixes to need about 3 to 4 million nodes, so a few hundred megabytes. Collapse single-child chains into one labelled edge (a radix trie), cap cached lists to the upper levels, and only index the terms that carry most of the traffic.
How do you keep suggestions fresh as popularity changes?
Rebuild the whole trie offline on a schedule and ship it as a file to every server, and patch hot changes in place by re-merging the cached lists along one word’s path. Rebuilding is cheap next to serving it, and shipping a file avoids a shared store on the hot path.
Why not just use the database with LIKE "sys%"?
With a B-tree index on the term column, LIKE with a leading literal is a range scan and works for exact prefixes. It cannot rank by popularity without reading every match, it is a network round trip per keystroke, and it does not handle per-prefix top-k. A trie in process answers in microseconds with the ranking built in.