Trie (prefix tree)
medium 20 minA trie (pronounced "try") is a tree that stores strings one character per level, so words with the same opening letters share the same path from the root.
Video lesson · Chapter 1 of 8
The sign maker’s catalogue
The trie in 75 seconds
1:19Reel
How it works
Step through the idea, or press Play.
One letter per level. Each edge is a character, so every path from the root spells a prefix
Understand it
Start here
A tree of letters
A trie (from retrieval, usually said "try") stores a set of strings as a tree. The root holds no letter. Each child edge adds one character, so the path from the root to any node spells a prefix, and a flag on the node says whether a whole word ends there. Words that start the same way share their path: cat, car, card and care all hang off one c → a chain.
What you already know
Tree DFS
Collecting every word below a node is a plain preorder DFS. Recap in tree DFS.
Hash maps
Each node keeps its children in a dict from letter to node: average per step. Recap in hash usage.
Sets and maps
A set answers "is this word stored?" but not "which words start with ca?". Recap in sets and maps.
The picture
One path per word
Trie for cat, car, card, care
| Node | Prefix it spells | is_end | Children |
|---|---|---|---|
| root | (empty) | False | c |
| c | c | False | a |
| a | ca | False | t, r |
| t | cat | True | none |
| r | car | True | d, e |
| d, e | card, care | True | none |
The node
Dict of children or a 26-slot array
| Dict of children | Array of 26 slots | |
|---|---|---|
| Child lookup | average (hashing) | exact: kids[ord(ch) - 97] |
| Memory per node | Only the children that exist | 26 pointers, most of them empty |
| Alphabet | Any character: Unicode, digits, spaces | Fixed, usually lowercase a to z |
| Children in order | Insertion order | Alphabetical for free |
| Typical use | Python interviews, real text | Fixed small alphabets, C++ and Java contests |
class DictNode: def __init__(self): self.children = {} # only letters that exist self.is_end = Falseclass ArrayNode: __slots__ = ("kids", "is_end") def __init__(self): self.kids = [None] * 26 # one slot per letter a..z self.is_end = Falsedef child(node, ch): return node.kids[ord(ch) - ord("a")]n = ArrayNode()n.kids[ord("c") - ord("a")] = ArrayNode()print(child(n, "c") is not None, child(n, "d")) # True NoneOperation 1
Insert
insert(word)
Insert car into a trie that holds cat
- 1
Letter c
At the root, child
calready exists (from cat). Step down, create nothing. - 2
Letter a
Child
aexists too. Step down. - 3
Letter r
No child
ryet: create it and step down. - 4
Mark the end
Letters used up: set
is_end = Trueon r. One new node for a three-letter word.
class TrieNode: def __init__(self): self.children = {} self.is_end = Falseclass Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for ch in word: if ch not in node.children: node.children[ch] = TrieNode() node = node.children[ch] node.is_end = True def _find(self, s): node = self.root for ch in s: if ch not in node.children: return None node = node.children[ch] return node def search(self, word): node = self._find(word) return node is not None and node.is_end def starts_with(self, prefix): return self._find(prefix) is not Nonet = Trie()t.insert("cat")t.insert("car")print(t.search("cat"), t.search("ca"), t.starts_with("ca")) # True False TrueOperations 2 and 3
Search vs starts_with
One walk, two answers
| Call (trie holds cat, car, card, care) | Path | Result | Why |
|---|---|---|---|
search('car') | c, a, r found | True | r is marked as an end |
search('ca') | c, a found | False | a is not an end: a prefix only |
search('cow') | breaks at o | False | c has no child o |
starts_with('ca') | c, a found | True | four words sit below a |
starts_with('do') | breaks at d | False | the root has no child d |
Operation 4
Delete without breaking other words
delete(word), recursively
Only unmark
Delete
carwhilecardandcareexist: r keeps its children, so just clearis_end.Prune a tail
Delete
card: d is a childless leaf, so it is cut off. Pruning stops at r because e still hangs below.Not present
Delete
dog: the root has no child d. Return without changing anything.
Complexity
O(L) per operation, O(total characters) space
| Operation | Time | Extra space |
|---|---|---|
insert(word) | up to new nodes | |
search(word) | ||
starts_with(prefix) | ||
delete(word) | recursion | |
| autocomplete | for the answers |
Time: one step per character
Space: at most one node per stored character
Application
Autocomplete: collect words under a prefix
Autocomplete in two phases
| Words in the trie | Prefix | Suggestions |
|---|---|---|
| app, apple, application, api, code, coding, computer, data, database | app | app, apple, application |
| cat, car, card, care, dog, dolphin, dove, bear, bee, bird | car | car, card, care |
| pizza, pie, pasta, pan, pancake, burger, burrito, bread, butter | pa | pasta, pan, pancake |
| how to code (1000), how to learn python (900), how to cook pasta (800), how are you (500), ... | how | ranked by count: how to code first |
class Node: def __init__(self): self.children = {} self.freq = 0 # > 0 means a query ends heredef add(root, text, freq): node = root for ch in text: node = node.children.setdefault(ch, Node()) node.freq = freqdef suggest(root, prefix, k=3): node = root for ch in prefix: if ch not in node.children: return [] node = node.children[ch] found = [] def dfs(n, text): if n.freq: found.append((-n.freq, text)) for ch, c in n.children.items(): dfs(c, text + ch) dfs(node, prefix) return [t for _, t in sorted(found)[:k]]root = Node()for q, f in [("how to code", 1000), ("how to cook pasta", 800), ("how to learn python", 900), ("how are you", 500), ("weather today", 2000)]: add(root, q, f)print(suggest(root, "how"))# ['how to code', 'how to learn python', 'how to cook pasta']Choosing
Trie vs hash set
| Question | Hash set of words | Trie |
|---|---|---|
Is word stored? | average (hash the word) | |
Any word starting with p? | : test every word | |
All words starting with p | ||
| Sorted order | No | Yes, with ordered children |
| Memory | One entry per word | One node per distinct prefix; can be larger |
| Code to write | None: set() is built in | A small class |
Use a trie when
- You need autocomplete or typeahead.
- Spell checking or suggestions by prefix.
- IP routing: longest prefix match.
- Word games: Boggle, word search, Scrabble helpers.
- Searching with wildcards such as
c.t.
Use something else when
- You only need exact lookups: a hash set or dict is simpler.
- Memory is tight: tries can be large.
- There are few strings and no prefix questions.
- You need ranges over numbers: a sorted array or balanced tree.
Classic problems
Word Search II and longest common prefix
Word Search II: given a letter grid and a list of words, find every word that can be traced through adjacent cells. Running one grid search per word repeats the same work. Instead, put all the words in a trie and run one backtracking DFS from each cell, moving down the trie as you move across the grid. The moment the current path is not a prefix of any word, the trie has no child for it and the branch is cut.
Word Search II: grid DFS guided by a trie
def longest_common_prefix(words): if not words: return "" root = {} END = "$" for w in words: node = root for ch in w: node = node.setdefault(ch, {}) node[END] = True prefix = [] node = root while len(node) == 1 and END not in node: ch = next(iter(node)) prefix.append(ch) node = node[ch] return "".join(prefix)print(longest_common_prefix(["flower", "flow", "flight"])) # flprint(longest_common_prefix(["car", "card", "care"])) # carProblems that are tries in disguise
Implement a trie
insert, search, starts_with: the three methods on this page.
Add and search with wildcards
A
.matches any letter: at that position, try every child.Word Search II
Many words on one grid: one DFS guided by a trie of all the words.
Replace words
Swap each word for its shortest root: walk until the first end flag.
In the wild
Where tries run
Search boxes
Google, Amazon and YouTube suggest completions as you type, ranked by how often each query is searched.
Spell checkers
Walk the trie to test a word and explore nearby branches for suggestions.
IP routing
Routers pick the most specific rule for an address with a longest-prefix match on a binary trie.
Word games
Boggle and Scrabble helpers prune any letter path that is not a prefix of a real word.
Recap
Key takeaways
Key points
- A trie stores strings one character per level; words with a common prefix share nodes.
- Each node has children (a dict or a 26-slot array) and an
is_endflag. - insert, search and starts_with are , independent of how many words are stored.
- search checks
is_end; starts_with does not. - Delete unmarks the end, then prunes nodes that are not ends and have no children.
- Space is at most one node per stored character, .
- Autocomplete is a prefix walk plus a DFS: .
- Prefer a hash set for exact lookups only; reach for a trie when prefixes matter.