Pattern 21 of 22
Trie Pattern: Template + 49 LeetCode Problems
Store a set of words by their shared prefixes so lookups cost the length of the word.
- Easy
- 3
- Medium
- 24
- Hard
- 22
What the trie pattern is
A trie stores a set of strings as a tree in which each edge is one character and each path from the root spells a prefix, so words sharing a prefix share the nodes that spell it. Lookup and insertion cost the length of the word and nothing else — the size of the dictionary does not appear in the complexity, which is why a trie beats a hash set for every question about prefixes rather than whole words. The node needs exactly two things: a map from character to child, and a flag saying a word ends here, because "car" being present must be distinguishable from "car" merely being a prefix of "cart". Two extensions cover most of the harder problems: storing a count or the best word at each node answers autocomplete queries without walking the subtree, and pairing a trie with a backtracking search over a grid prunes whole regions the moment the prefix stops existing, which is what makes a word-search-over-a-dictionary tractable.
When to use it
- Queries are about prefixes: autocomplete, "does any word start with…", longest common prefix.
- A large dictionary is searched many times and repeated prefix work is the bottleneck.
- A backtracking search over a grid or a string needs to be pruned by a word list.
- Wildcards must be matched inside words, where a hash set cannot help at all.
The trie template in Python
The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 49 problems listed below.
class Trie:
def __init__(self):
self.children = {}
self.is_word = False # "car" present vs. "car" merely a prefix of "cart"
def insert(self, word):
node = self
for char in word:
node = node.children.setdefault(char, Trie())
node.is_word = True
def find(self, prefix):
"""The node reached by prefix, or None. is_word tells you if it is a word."""
node = self
for char in prefix:
node = node.children.get(char)
if node is None:
return None
return nodeComplexity characteristics
- Time
- O(L) per insert or lookup, where L is the length of the word
- Auxiliary space
- O(total characters stored)
The cost of a lookup is the length of the key and nothing else — the number of words already stored does not appear in it, which is the property a hash set cannot match for prefix queries. The space is one node per distinct prefix, so a dictionary with heavy prefix sharing costs far less than the sum of its word lengths and one with none costs exactly that sum. Pairing a trie with a grid search prunes the moment a prefix stops existing, which changes the observed cost by orders of magnitude without changing the worst case.
Eyes only
Meet the trie problem you did not practise.
In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.
All 49 trie LeetCode problems
Every problem in the library the trie pattern applies to, grouped by LeetCode's own difficulty rating. 36 of the 49 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.
Related LeetCode topics
Easy (3)
| No. | Problem | Topics |
|---|---|---|
| 0014 | Longest Common Prefix | |
| 1065 | Index Pairs of a StringPremium | |
| 2932 | Maximum Strong Pair XOR I |
Medium (24)
| No. | Problem | Topics |
|---|---|---|
| 0139 | Word Break | |
| 0208 | Implement Trie (Prefix Tree) | |
| 0211 | Design Add and Search Words Data Structure | |
| 0386 | Lexicographical Numbers | |
| 0421 | Maximum XOR of Two Numbers in an Array | |
| 0648 | Replace Words | |
| 0676 | Implement Magic Dictionary | |
| 0677 | Map Sum Pairs | |
| 0692 | Top K Frequent Words | |
| 0720 | Longest Word in Dictionary | |
| 1268 | Search Suggestions System | |
| 0616 | Add Bold Tag in StringPremium | |
| 0758 | Bold Words in StringPremium | |
| 0792 | Number of Matching Subsequences | |
| 0820 | Short Encoding of Words | |
| 1023 | Camelcase Matching | |
| 1166 | Design File SystemPremium | |
| 1233 | Remove Sub-Folders from the Filesystem | |
| 1698 | Number of Distinct Substrings in a StringPremium | |
| 1804 | Implement Trie II (Prefix Tree)Premium | |
| 1858 | Longest Word With All PrefixesPremium | |
| 2261 | K Divisible Elements Subarrays | |
| 2452 | Words Within Two Edits of Dictionary | |
| 2707 | Extra Characters in a String |
Hard (22)
| No. | Problem | Topics |
|---|---|---|
| 0140 | Word Break II | |
| 0212 | Word Search II | |
| 0336 | Palindrome Pairs | |
| 0440 | K-th Smallest in Lexicographical Order | |
| 0472 | Concatenated Words | |
| 0745 | Prefix and Suffix Search | |
| 0425 | Word SquaresPremium | |
| 0527 | Word AbbreviationPremium | |
| 0588 | Design In-Memory File SystemPremium | |
| 0642 | Design Search Autocomplete SystemPremium | |
| 1032 | Stream of Characters | |
| 1178 | Number of Valid Words for Each Puzzle | |
| 1316 | Distinct Echo Substrings | |
| 1707 | Maximum XOR With an Element From Array | |
| 1803 | Count Pairs With XOR in a Range | |
| 1938 | Maximum Genetic Difference Query | |
| 1948 | Delete Duplicate Folders in System | |
| 2227 | Encrypt and Decrypt Strings | |
| 2416 | Sum of Prefix Scores of Strings | |
| 2479 | Maximum XOR of Two Non-Overlapping SubtreesPremium | |
| 2935 | Maximum Strong Pair XOR II | |
| 2977 | Minimum Cost to Convert String II |
Trie pattern FAQ
What is the trie pattern?
A trie stores a set of strings as a tree in which each edge is one character and each path from the root spells a prefix, so words sharing a prefix share the nodes that spell it.
How many LeetCode problems use the trie pattern?
This page lists 49 LeetCode problems that the trie pattern applies to: 3 Easy, 24 Medium and 22 Hard. 36 of them carry a complete Python solution with complexity analysis.
What is the time complexity of the trie pattern?
O(L) per insert or lookup, where L is the length of the word time and O(total characters stored) space. The cost of a lookup is the length of the key and nothing else — the number of words already stored does not appear in it, which is the property a hash set cannot match for prefix queries. The space is one node per distinct prefix, so a dictionary with heavy prefix sharing costs far less than the sum of its word lengths and one with none costs exactly that sum. Pairing a trie with a grid search prunes the moment a prefix stops existing, which changes the observed cost by orders of magnitude without changing the worst case.
When should I use the trie pattern in an interview?
Queries are about prefixes: autocomplete, "does any word start with…", longest common prefix. A large dictionary is searched many times and repeated prefix work is the bottleneck.
Which trie problem should I start with?
LeetCode 14. Longest Common Prefix is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.
What patterns are related to trie?
Hash Map, Backtracking, Tree Traversal, Depth-First Search. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.
More ways in: all 22 patterns, the curated study lists, or the full problem list.