SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
  • Inverted Index
  • Trie (Prefix Tree)
  • LRU Cache Design
  • Heap and Priority Queue
  • Bitmaps and Roaring Bitmaps
  • Ring Buffer
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Advanced Data Topics/Data Structures for Scale

Trie (Prefix Tree)

A tree where each step is one letter, so finding every word that starts with 'ca' is instant. The heart of autocomplete.

⏱ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

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.

  • Insert, search and starts-with all cost O(L), where L is the length of the word. The number of stored words does not matter.
  • Autocomplete: store the top few suggestions on each node, so a lookup is just "walk the prefix, read the list".
  • Cost: many small nodes use a lot of memory. Compressed (radix) tries and sharding by prefix fix that.

02Concept: What is it?

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.

Words that share a start share a path
•root
→↓c
🔤c
→↓a
🔤a
→↓r
✅r (car)then d, e, t
car, card, care and cart use the same three nodes, then split. Green nodes end a word.

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.

🧠Cost depends on the typed length
Looking up "ca" takes 2 steps, whether the trie holds ten words or ten billion. This is why tries power typeahead.

03Real-Life Example

🍵The Dictionary Thumb Tabs
A paper dictionary has thumb tabs. You do not scan the book for words starting with "ca". You flip to the C tab, then to the CA section, and every word from there to the end of that section is a match. A trie is that tab system, repeated for every letter, all the way down.
Dictionary
Trie
The C tab
The child node for c
Then the CA section
The child node for a under c
Every word in that section
Every word in that subtree
A bookmark “most used words here”
Top-K list cached on the node
The end of a full word
The end-of-word flag
Sections that never branch
A compressed (radix) edge
One typeahead request
⌨️User types “ca”
→↓prefix
🌳Trie servicewalk c, a
→↓stored top 3
📋cat, car, care
The browser sends the prefix. The service walks the trie and returns the stored list.

04Why Do We Need It?

⚡Prefix queries are native
“Everything that starts with...” is one walk, not a scan.
📏Cost is the word length
Independent of how many words are stored.
🗜️Shared prefixes are stored once
Many words with the same start save space compared with storing each in full.
🔤Sorted order for free
Walking children in letter order gives words in alphabetical order.
🧭Fast misses
If a letter has no child, you stop at once.
🧮Top-K in O(L)
Cached top results make suggestions as fast as one lookup.
When the question is about the beginning of a word, a trie answers by walking, not by searching.

05Where Do We Use It?

⌨️Search autocomplete
Suggest queries as the user types, in search boxes and address bars.
📱Phone keyboards and contacts
Word prediction and name lookup.
🌐IP routing
Longest-prefix match in routers uses a trie of address bits.
🛣️URL routers
Web frameworks match a request path against route segments in a trie.
📖Spell check and dictionaries
Word lists and suggestions for near matches.
🔎Search term dictionary
Search engines store their sorted term list in a trie-like structure.

06Types / Parts / How It Works

The basic operations

OperationHow it worksCost
Insert wordWalk letters, create missing nodes, set the end flagO(L)
Search exact wordWalk letters, check the end flagO(L)
Starts-withWalk the prefix letters, just check the path existsO(L)
List all with prefixWalk the prefix, then visit the whole subtreeO(L + size of subtree)
Top-K with prefixWalk the prefix, read the list cached on the nodeO(L + K)
DeleteClear the flag, then remove nodes that are now unusedO(L)

Shapes of tries

TypeIdeaGood forWatch out
Plain trieOne node per letterLearning, small setsLots of memory
Compressed (radix / Patricia) trieMerge a chain of single-child nodes into one edge with a stringLarge word lists, routersSplitting edges on insert is fiddly
Ternary search treeEach node has three links (less, equal, more)Saves space on wide alphabetsA bit slower than a trie
Double-array / FSTPacked arrays or automataSearch engine term dictionariesHard to update, build offline
Compressing a chain
Plain trie
🔤r → o → m → a → n5 nodes for “roman”
Radix trie
🔤“roman” on one edge1 node
Nodes with only one child can be merged into one edge that holds a string.
One letter per node Strings on edges, fewer nodes

Autocomplete at scale

  • Build offline: count queries from logs (a batch or stream job), build the trie with top-K lists, and ship it. Do not rebuild on every search.
  • Shard by prefix: for example, servers for a to f, g to m, and so on. Split busy prefixes further ("s" and "th" are heavy).
  • Cache hot prefixes: the first one to three letters get most of the traffic. Put them in the browser, a CDN or Redis.
  • Refresh slowly: swap in a new trie hourly or daily. Fresh trends can be added through a small second trie.
VisualizerWalk a prefix and read the suggestionsPick or type a prefix and watch the cyan path. Then switch between “Top 3 cached at each node” and “Walk the whole subtree”, and compare how many nodes must be visited.
Type a prefix (or pick one)
How are suggestions found?
•canprdettdogort
● path of your prefix● where you stopped● a word ends here
Top 3 suggestions for “ca”
cat (120)car (90)care (75)
Steps down
2
one per letter typed
Nodes below visited
0
none needed
Nodes in trie
16
10 words
Walked 2 nodes down (one per letter), then read the 3 suggestions stored on that node. Nothing below it was visited, so the cost depends on the length of what you typed, not on how many words exist.

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.

07How to Use It / Steps / Implementation

Building a typeahead service

  1. 1
    Collect query counts
    Log what people search. Count each query over a time window.
  2. 2
    Clean and filter
    Lowercase, drop rude or private terms, and drop very rare queries.
  3. 3
    Build the trie
    Insert each query with its count at the end node.
  4. 4
    Cache the top K on each node
    Bottom-up: a node’s list is the best K of its own word and its children’s lists.
  5. 5
    Serve by walking
    On each keystroke, walk the prefix and return the stored list. Debounce on the client so you do not send every key.
  6. 6
    Shard and replicate
    Split by prefix across servers, with copies for failover.
  7. 7
    Swap in new versions
    Build a new trie offline and switch over. Keep the old one for rollback.
A small trie in TypeScript
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
}
💡Store IDs, not strings
Keep each top-K list as short IDs into one table of phrases. Hundreds of thousands of nodes then share the same strings.

08Key Terms to Know

TermMeaning in easy words
Trie / prefix treeA tree where each edge is a letter and paths spell words
PrefixThe first few letters of a word
RootThe empty top node
End-of-word flagA mark saying a full word finishes at this node
Radix (Patricia) trieA trie where chains of single-child nodes are merged into one edge
Ternary search treeA trie variant with three links per node (less, equal, more)
Top-K cacheThe best K words stored on each node for instant suggestions
TypeaheadSuggestions that appear as the user types
DebounceWait for a short pause in typing before sending a request
Longest-prefix matchFinding the longest stored prefix of an input, as routers do
FSTFinite state transducer, a very compact trie-like structure used in Lucene

09Pros, Cons and Trade-offs

✅ Pros
  • O(L) for insert, search and prefix, independent of the number of words
  • Prefix and autocomplete queries are natural
  • Words come out in sorted order
  • Top-K caching gives constant-time suggestions
  • Easy to shard by prefix
⚠️ Cons
  • Plain tries use a lot of memory (many small nodes and pointers)
  • Poor cache locality: chasing pointers
  • Cached top-K lists must be rebuilt when counts change
  • Not good for suffix or middle-of-word matches
  • Unicode and big alphabets widen the nodes

Trade-offs

ChoiceWe gainWe lose
Trie vs hash mapPrefix queriesMemory and plain exact-lookup speed
Cache top-K per nodeConstant-time suggestionsSpace and rebuild work
Radix compressionFar fewer nodesMore complex inserts
Child array vs mapArray: fast. Map: smallArray wastes space on sparse nodes
Offline rebuildSimple and stableSuggestions lag behind trends
Shard by prefixSpreads data and loadHot prefixes need extra splits

10Common Problems and Mistakes

Common mistakes

  1. Walking the whole subtree on every key. It works in a demo and melts under real traffic. Cache top-K.
  2. Updating the live trie for every search. It causes lock contention and constant list recomputation. Count in a log, rebuild in batches.
  3. Forgetting the end flag. "car" and "card" look the same without it, and "ca" looks like a word.
  4. Using an array of 26 children everywhere. Most nodes have one or two children, so memory explodes. Use a map or a radix trie.
  5. No cleaning of input. Case, spaces and accents produce separate paths for the same word.
  6. One server for all prefixes. The first letters get most of the traffic. Shard and cache.
  7. Showing unsafe suggestions. Autocomplete can surface private or offensive text. Filter before building.

Things to watch

🧠Memory size
Estimate nodes times pointer size before choosing a plain trie.
⌨️Request volume
Without debounce, every key is a request. Typing 10 letters means 10 calls.
📈Fresh trends
A new event needs a way to appear before the next rebuild.
🌍Languages
Other scripts need Unicode-aware splitting, and sometimes word-level tries.

11Real-World Examples

🔍Google and Bing suggestions
Query suggestions are built from logs, ranked, filtered and served from prefix structures.
🪶Lucene FST
The term dictionary is a compact finite state transducer, which is a trie squeezed hard.
🧰Redis
Radix trees (rax) hold keys and streams inside Redis.
🌐Routers
Forwarding tables use longest-prefix match on a binary trie.
🛠️Web frameworks
Many routers, such as those in Go and Node, match paths with a radix tree.
📱Mobile keyboards
Word prediction uses tries or similar structures, with learned usage counts.
Mini case: typeahead for a big site
⌨️Keystrokedebounced
→↓prefix “ca”
⚡Edge cachehot prefixes
→↓miss
🌳Trie shard for ctop 5 on the node
Hot prefixes are answered by a cache. The rest go to the trie shard for that prefix.

12Related Topics to Read Next

Inverted Index→

The other great text structure: word to documents.

Full-Text Search Engines→

Uses trie-like term dictionaries and prefix queries.

Heap and Priority Queue→

Used to keep the top K results while merging.

Sharding→

How to split a big trie across servers by prefix.

Caching Strategies→

Caching the hottest prefixes at the edge.

Batch vs Stream Processing→

How query counts are collected and the trie is rebuilt.

Bloom Filters→

A tiny way to say a word is definitely not present.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Shape: one letter per edge, end flag where a word finishes.
  • ✔Cost: insert, search and starts-with are O(L).
  • ✔Autocomplete: walk the prefix, read the top-K cached on the node.
  • ✔Save memory: radix trie, maps for children, IDs not strings.
  • ✔Scale: build offline, shard by prefix, cache hot prefixes, debounce.
  • ✔Not for: suffix or middle-of-word search.
  • ✔Also used in: IP routing, URL routers, term dictionaries.
  • ✔One line: “Let the letters be the path, and the answer is whatever hangs below.”
← Previous
Inverted Index
Next →
LRU Cache Design