Trie Pattern: Template + 49 LeetCode Problems
Store a set of words by their shared prefixes so lookups cost the length of the word.
- 3 Easy
- 24 Medium
- 22 Hard
- O(L) per insert or lookup, where L is the length of the word time
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.
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.
Easy (3)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 14 | Longest Common Prefix | Easy | Trie, Array, String |
| 1065 | Index Pairs of a StringPremium | Easy | Trie, Array, String +1 |
| 2932 | Maximum Strong Pair XOR I | Easy | Bit Manipulation, Trie, Array +2 |
Medium (24)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 139 | Word Break | Medium | Trie, Memoization, Array +3 |
| 208 | Implement Trie (Prefix Tree) | Medium | Design, Trie, Hash Table +1 |
| 211 | Design Add and Search Words Data Structure | Medium | Depth-First Search, Design, Trie +1 |
| 386 | Lexicographical Numbers | Medium | Depth-First Search, Trie |
| 421 | Maximum XOR of Two Numbers in an Array | Medium | Bit Manipulation, Trie, Array +1 |
| 648 | Replace Words | Medium | Trie, Array, Hash Table +1 |
| 676 | Implement Magic Dictionary | Medium | Depth-First Search, Design, Trie +2 |
| 677 | Map Sum Pairs | Medium | Design, Trie, Hash Table +1 |
| 692 | Top K Frequent Words | Medium | Trie, Array, Hash Table +5 |
| 720 | Longest Word in Dictionary | Medium | Trie, Array, Hash Table +2 |
| 1268 | Search Suggestions System | Medium | Trie, Array, String +3 |
| 616 | Add Bold Tag in StringPremium | Medium | Trie, Array, Hash Table +2 |
| 758 | Bold Words in StringPremium | Medium | Trie, Array, Hash Table +2 |
| 792 | Number of Matching Subsequences | Medium | Trie, Array, Hash Table +4 |
| 820 | Short Encoding of Words | Medium | Trie, Array, Hash Table +1 |
| 1023 | Camelcase Matching | Medium | Trie, Array, Two Pointers +2 |
| 1166 | Design File SystemPremium | Medium | Design, Trie, Hash Table +1 |
| 1233 | Remove Sub-Folders from the Filesystem | Medium | Depth-First Search, Trie, Array +1 |
| 1698 | Number of Distinct Substrings in a StringPremium | Medium | Trie, String, Suffix Array +2 |
| 1804 | Implement Trie II (Prefix Tree)Premium | Medium | Design, Trie, Hash Table +1 |
| 1858 | Longest Word With All PrefixesPremium | Medium | Depth-First Search, Trie, Array +1 |
| 2261 | K Divisible Elements Subarrays | Medium | Trie, Array, Hash Table +3 |
| 2452 | Words Within Two Edits of Dictionary | Medium | Trie, Array, String |
| 2707 | Extra Characters in a String | Medium | Trie, Array, Hash Table +2 |
Hard (22)
| # | Problem | Difficulty | Topics |
|---|---|---|---|
| 140 | Word Break II | Hard | Trie, Memoization, Array +4 |
| 212 | Word Search II | Hard | Trie, Array, String +2 |
| 336 | Palindrome Pairs | Hard | Trie, Array, Hash Table +1 |
| 440 | K-th Smallest in Lexicographical Order | Hard | Trie |
| 472 | Concatenated Words | Hard | Depth-First Search, Trie, Array +3 |
| 745 | Prefix and Suffix Search | Hard | Design, Trie, Array +2 |
| 425 | Word SquaresPremium | Hard | Trie, Array, String +1 |
| 527 | Word AbbreviationPremium | Hard | Greedy, Trie, Array +2 |
| 588 | Design In-Memory File SystemPremium | Hard | Design, Trie, Hash Table +2 |
| 642 | Design Search Autocomplete SystemPremium | Hard | Depth-First Search, Design, Trie +4 |
| 1032 | Stream of Characters | Hard | Design, Trie, Array +2 |
| 1178 | Number of Valid Words for Each Puzzle | Hard | Bit Manipulation, Trie, Array +2 |
| 1316 | Distinct Echo Substrings | Hard | Trie, String, Hash Function +1 |
| 1707 | Maximum XOR With an Element From Array | Hard | Bit Manipulation, Trie, Array |
| 1803 | Count Pairs With XOR in a Range | Hard | Bit Manipulation, Trie, Array |
| 1938 | Maximum Genetic Difference Query | Hard | Bit Manipulation, Depth-First Search, Trie +2 |
| 1948 | Delete Duplicate Folders in System | Hard | Trie, Array, Hash Table +2 |
| 2227 | Encrypt and Decrypt Strings | Hard | Design, Trie, Array +2 |
| 2416 | Sum of Prefix Scores of Strings | Hard | Trie, Array, String +1 |
| 2479 | Maximum XOR of Two Non-Overlapping SubtreesPremium | Hard | Tree, Depth-First Search, Graph +1 |
| 2935 | Maximum Strong Pair XOR II | Hard | Bit Manipulation, Trie, Array +2 |
| 2977 | Minimum Cost to Convert String II | Hard | Graph, Trie, Array +3 |
Related patterns
Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.
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.
Meet the trie problem you did not practise
Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.