A trie (pronounced "try", from re*trie*val), also called a prefix tree, stores strings one character per level. Every path from the root spells a prefix, and words that share a beginning share the same path. Insert, search and prefix checks cost O(L) for a key of length L, no matter how many words are stored, which makes tries the natural structure for autocomplete, spell checking, IP routing and word games.
Think of it like
A thumb-indexed dictionary
To find "cart" in a big paper dictionary, you open the C tab, then the CA section, then CAR, and finally spot CART. Every word starting with "car" (car, card, care, cart) lives in the same section, so the shared beginning is printed once in the index. A trie is that index taken to the limit: one tab per letter, all the way down.
How a trie is organized
The root represents the empty string. Each node has up to Σ children (Σ is the alphabet size), one per possible next character, and a boolean end-of-word flag. The flag matters because a word can be a prefix of another: "car" is a prefix of "card", and the trie must remember whether "car" itself was inserted.
(root)
/ \
c d
| |
a o*
/ \ |
r* t* g*
/ \
d* e*
* = end of a wordNode structure: array or map children?
Fixed array (e.g. 26 slots)
- O(1) child access by
ch - 'a', no hashing - Children are naturally in alphabetical order
- 26 pointers per node (about 208 bytes on 64-bit) even if one is used
- Only practical for small, known alphabets
Hash map (or sorted map)
- Memory proportional to the children that actually exist
- Handles Unicode, mixed case, any symbol set
- Hashing overhead and worse cache behavior
- Sort the keys (or use a sorted map) for alphabetical output
Middle grounds exist: a sorted array of (char, child) pairs, bitmap-indexed nodes, or a ternary search tree, where each node holds one character plus less, equal and greater pointers.
Core operations
| Operation | Walk | Result |
|---|---|---|
insert(word) | Follow each character, creating missing children | Mark the final node as end-of-word |
search(word) | Follow each character; stop if a child is missing | True only if the final node is marked end-of-word |
startsWith(prefix) | Same walk as search | True if the walk completes, whatever the flag says |
delete(word) | Walk to the final node, recording the path | Unmark it, then prune childless, unmarked nodes bottom-up |
Deletion and pruning
- 1
Find the word
Walk down, remembering each node on the path. If a character is missing or the last node is not marked, the word is not present.
- 2
Unmark
Clear the end-of-word flag on the last node.
- 3
Prune upward
Moving back toward the root, remove each node that has no children and is not the end of another word.
- 4
Stop early
The first node that still has children or marks another word must stay, and so must everything above it. Deleting "card" removes only
d; deleting "car" removes nothing but the flag.
Complexity and memory trade-offs
Every operation touches one node per character, so insert, search and prefix checks are O(L). A hash set also needs O(L) just to hash the key, so a trie is not asymptotically faster for exact lookups. Its real advantages are prefix queries and ordered traversal.
| Structure | Exact lookup | All keys with a prefix | Sorted iteration | Memory |
|---|---|---|---|---|
| Hash set | O(L) average | O(n · L): scan everything | No | Compact |
| Balanced BST / sorted array | O(L log n) | O(L log n + output): range scan | Yes | Compact |
| Trie | O(L) | O(L + output) | Yes, by DFS | High: up to one node per character |
Nodes, worst case
N + 1
N = total characters inserted
Array node (a-z, 64-bit)
≈ 210 B
26 pointers plus a flag
100k words × 8 chars
≈ 168 MB
array nodes, no prefix sharing
Compressed tries (radix trees)
Long chains of single-child nodes waste space. A radix tree (compact prefix tree) merges each chain into one edge labeled with a whole substring. Every internal node then has at least two children unless it marks a word, so a radix tree over n words has at most 2n nodes regardless of word length. A PATRICIA trie is the binary version, branching on individual bits.
(root)
/ \
"ca" "do"*
/ \ \
"r"* "t"* "g"*
/ \
"d"* "e"*Radix trees show up in the Linux page cache (the XArray), in HTTP routers that match URL paths, in IP routing tables, and in Ethereum's Merkle Patricia trie for account state.
Applications
Autocomplete
Walk to the node for the typed prefix in O(L), then DFS below it to collect completions. Production systems store a precomputed list of the top-k most popular completions at each node, so a keystroke costs a single walk with no DFS at all. The Design Search Autocomplete case study scales this idea up.
Spell checking and fuzzy search
To suggest words within edit distance k, DFS the trie while maintaining one row of the edit-distance table (see LCS & Edit Distance) per node. Words sharing a prefix share those rows, and a branch is abandoned as soon as every value in its row exceeds k.
Longest-prefix match in IP routing
A routing table maps address prefixes to next hops. Store the prefixes in a binary trie over address bits. To route a packet, walk down along the destination address's bits and remember the last node that carried a route: that is the most specific match.
| Destination | Matching routes | Chosen route |
|---|---|---|
10.1.2.3 | 0.0.0.0/0, 10.0.0.0/8, 10.1.0.0/16 | 10.1.0.0/16 (longest) |
10.2.0.1 | 0.0.0.0/0, 10.0.0.0/8 | 10.0.0.0/8 |
8.8.8.8 | 0.0.0.0/0 | The default route |
Word Search II
Given a letter grid and a dictionary, find every dictionary word that can be traced through adjacent cells. Searching for each word separately repeats work. Instead, insert all words into a trie and run a single Backtracking DFS from every cell, advancing through the trie in lockstep with the grid. When the current path is not a prefix of any word, the trie has no child for that letter and the branch dies immediately.
Maximum XOR of two numbers
Insert each number into a binary trie as its bits, most significant first. To find the best partner for x, walk down and at each level prefer the child holding the opposite bit, because a 1 in a higher position is worth more than all lower positions combined. The greedy walk is optimal and costs O(B) per number for B-bit integers (see Bit Manipulation).
Complexity
| Operation | Time | Space | Notes |
|---|---|---|---|
| Insert a word of length L | O(L) | O(L) | At most L new nodes |
| Search / startsWith | O(L) | O(1) | Independent of the number of words |
| Delete | O(L) | O(L) | Path stack for bottom-up pruning |
| Autocomplete a prefix of length p | O(p + k) | O(k) | k = total characters in the returned words |
| Build from words with N total characters | O(N) | O(N) | Times Σ pointers per node with array children |
| Max XOR pair over n B-bit numbers | O(n · B) | O(n · B) | One insert and one greedy walk per number |
L = key length, N = total characters inserted, Σ = alphabet size. The number of stored words never appears in the per-operation bounds.
Implementation
Map-based children. Delete records the path and prunes bottom-up. Java and C++ use sorted maps so autocomplete returns words alphabetically; Python and TypeScript sort the keys during the DFS.
class TrieNode:
__slots__ = ("children", "is_end")
def __init__(self):
self.children: dict[str, "TrieNode"] = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for ch in word:
node = node.children.setdefault(ch, TrieNode())
node.is_end = True
def _walk(self, s: str):
node = self.root
for ch in s:
node = node.children.get(ch)
if node is None:
return None
return node
def search(self, word: str) -> bool:
node = self._walk(word)
return node is not None and node.is_end # must END here, not just pass through
def starts_with(self, prefix: str) -> bool:
return self._walk(prefix) is not None
def delete(self, word: str) -> bool:
path = [self.root] # path[i + 1] is reached via word[i]
for ch in word:
nxt = path[-1].children.get(ch)
if nxt is None:
return False
path.append(nxt)
if not path[-1].is_end:
return False
path[-1].is_end = False
for i in range(len(word) - 1, -1, -1): # prune bottom-up
node = path[i + 1]
if node.children or node.is_end:
break # still needed by another word
del path[i].children[word[i]]
return True
def with_prefix(self, prefix: str, limit: int = 10) -> list[str]:
out: list[str] = []
def dfs(node: TrieNode, acc: str) -> None:
if len(out) >= limit:
return
if node.is_end:
out.append(acc)
for ch in sorted(node.children): # alphabetical order
dfs(node.children[ch], acc + ch)
start = self._walk(prefix)
if start:
dfs(start, prefix)
return out
t = Trie()
for w in ["car", "card", "care", "cat", "do", "dog"]:
t.insert(w)
print(t.search("ca"), t.starts_with("ca"), t.with_prefix("car"))
# False True ['car', 'card', 'care']Key takeaways
- A trie stores strings as root-to-node paths, one character per level; shared prefixes are stored once.
- Insert, search and startsWith cost O(L) for a key of length L, independent of how many keys are stored.
- An end-of-word flag separates complete words from mere prefixes; search checks it, startsWith does not.
- Tries trade memory for speed: array children are fast but heavy, map children are lean but slower, and radix trees compress single-child chains.
- Signature uses: autocomplete, spell checking, longest-prefix IP routing, Word Search II and maximum XOR with a binary trie.
Common pitfalls
- Returning true from
searchwhenever the walk succeeds, without checking the end-of-word flag. - Deleting nodes that other words still need, for example removing the whole
c-a-rpath when deleting "card" while "car" is stored. - Allocating 26-slot arrays for a Unicode or mixed-case alphabet, which either crashes on unexpected characters or wastes enormous memory.
- In Word Search II, restarting a fresh trie walk for every grid cell and word instead of advancing one trie pointer alongside the DFS.
- Building the max-XOR trie with too few bits, or from the least significant bit first, which breaks the greedy argument.
Interview tips
- Write the node class first (children plus
isEnd); interviewers look for that flag. - Quote complexity in terms of L (key length) and mention memory as the main cost, along with radix trees as the fix.
- For multi-word grid or dictionary problems, explain how the trie prunes the search: a missing child ends the branch immediately.
- When a problem asks to maximize XOR, sketch the binary trie and the "take the opposite bit if it exists" greedy rule.
Real-world applications
- Search-box autocomplete and query suggestions, often with top-k results cached per node.
- Spell checkers and fuzzy matching over a dictionary.
- Longest-prefix-match forwarding tables in routers.
- Text input methods, T9 keypads and word games such as Boggle and Scrabble solvers.
- Compressed variants in the Linux page cache, HTTP routers and Ethereum's state trie.
Practice problems
Test yourself
A trie contains only the word "card". What do search("car") and startsWith("car") return?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.