Trie (Prefix Tree)
Data StructuresEfficient prefix matching, autocomplete, and dictionary lookups
53 problems·4 Easy·27 Medium·22 Hard
Pattern Study Guide & Cheat Sheet▼
Tree structure where paths from root represent string prefixes, allowing prefix searches, autocomplete, and dictionary lookups in O(L) time proportional to word length.
Core Invariant: Each node represents a character transition. A node contains children `char -> TrieNode` and a boolean flag `is_end = True` indicating if a complete word terminates at that node.
Recognize it (Keywords & Signals)
- Prefix search / implement startsWith(prefix)
- Word search board with dictionary / Boggle game
- Autocomplete / search suggestions / spell checker
- Replace words with shortest root
- Maximum XOR pair in an array (Binary Bitwise Trie)
When NOT to use
Exact lookups only with no prefix queries (standard Hash Set has less memory overhead and O(1) expected time).
How to solve (Step-by-step)
- 1.Define `TrieNode` with `children = {}` and `is_end = False`.
- 2.Insert: walk character by character. If character not in `curr.children`, create new node. Mark last node `is_end = True`.
- 3.Search: walk characters. If any character missing, return False. If all found, return `curr.is_end`.
- 4.StartsWith: walk characters. If any missing, return False. If found, return True regardless of `is_end`.
Watch for (Interview Traps)
- Confusing `search` (requires `node.is_end == True`) with `starts_with` (only requires node exists)
- Memory explosion: in Python, using `dict` children is more memory-efficient than `[None] * 26`
- Word Search II TLE: forget to remove found words from Trie or mark already visited grid cells
Prefix Tree (Trie) Implementation
class TrieNode:
def __init__(self):
self.children: dict[str, TrieNode] = {}
self.is_end: bool = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
curr = self.root
for char in word:
if char not in curr.children:
curr.children[char] = TrieNode()
curr = curr.children[char]
curr.is_end = True
def search(self, word: str) -> bool:
node = self._traverse(word)
return node is not None and node.is_end
def starts_with(self, prefix: str) -> bool:
return self._traverse(prefix) is not None
def _traverse(self, prefix: str) -> TrieNode | None:
curr = self.root
for char in prefix:
if char not in curr.children:
return None
curr = curr.children[char]
return curr- Cost
- O(L) per insert/search where L is word length · O(total characters * alphabet size) (Lookup speed is completely independent of the number of words stored in the Trie.)
Canonical problems
#208 Implement Trie (Prefix Tree): Foundational insert, search, and startsWith operations
#211 Design Add and Search Words Data Structure: DFS on Trie branches to handle "." wildcard queries
#212 Word Search II: Traverse 2D matrix with Trie to prune invalid prefixes immediately
#421 Maximum XOR of Two Numbers in an Array: Bitwise 0/1 Trie picks opposite bits greedily
⌘K
Medium·19 companies·Max freq 100%·Acc 65.2%
Squarepoint CapitalUBSDoorDash+16
Medium·17 companies·Max freq 100%·Acc 62.3%
The Trade DeskZipRecruiterVisa+14
Medium·16 companies·Max freq 88%·Acc 48.7%
DatadogNeetCode 150NeetCode 150+13
Hard·13 companies·Max freq 75%·Acc 50.0%
RobloxPinterestMongoDB+10
Medium·8 companies·Max freq 88%·Acc 78.6%
VerkadaNuroSnowflake+5
Easy·7 companies·Max freq 100%·Acc 77.8%
AutodeskFICOCapital One+4
Hard·7 companies·Max freq 100%·Acc 46.4%
HuluDE ShawGoogle+4
Hard·7 companies·Max freq 88%·Acc 77.4%
Booking.comBooking.comNvidia+4
Medium·5 companies·Max freq 38%·Acc 53.6%
GoogleBloombergAmazon+2
Hard·4 companies·Max freq 100%·Acc 28.7%
AutodeskSamsungCapital One+1
Medium·4 companies·Max freq 100%·Acc 64.7%
DunzoIntuitUber+1
Hard·4 companies·Max freq 63%·Acc 59.6%
AtlassianAmazonMicrosoft+1
Medium·4 companies·Max freq 25%·Acc 73.4%
MetaGoogleBloomberg+1
Medium·3 companies·Max freq 100%·Acc 51.1%
MoveworksAffirmAirbnb
# | Problem | Difficulty | Top Companies↓ | Frequency | Acceptance | |
|---|---|---|---|---|---|---|
| #14 | Longest Common Prefix ArrayStringTrie | Easy | 100% | 47.9% | ||
| #139 | Word Break ArrayHash TableStringDynamic ProgrammingTrieMemoizationBrute-Force Search | Medium | 100% | 49.6% | ||
| #208 | Implement Trie (Prefix Tree) Hash TableStringDesignTrie | Medium | 100% | 0.7% | ||
| #692 | Top K Frequent Words ArrayHash TableStringTrieSortingHeap (Priority Queue)Bucket SortCounting | Medium | 100% | 60.4% | ||
| #212 | Word Search II ArrayStringBacktrackingTrieMatrix | Hard | 89% | 38.6% | ||
| #1268 | Search Suggestions System ArrayStringBinary SearchTrieSortingHeap (Priority Queue) | Medium | 100% | 65.2% | ||
| #140 | Word Break II ArrayHash TableStringDynamic ProgrammingBacktrackingTrieMemoization | Hard | 100% | 55.8% | ||
| #3043 | Find the Length of the Longest Common Prefix ArrayHash TableStringTrie | Medium | 100% | 62.3% | ||
| #588 | Design In-Memory File System Hash TableStringDesignTrieSorting | Hard | 100% | 48.3% | ||
| #211 | Design Add and Search Words Data Structure StringDepth-First SearchDesignTrie | Medium | 88% | 48.7% | ||
| #642 | Design Search Autocomplete System StringDepth-First SearchDesignTrieSortingHeap (Priority Queue)Data Stream | Hard | 75% | 50.0% | ||
| #1166 | Design File System Hash TableStringDesignTrie | Medium | 75% | 65.2% | ||
| #792 | Number of Matching Subsequences ArrayHash TableStringBinary SearchDynamic ProgrammingTrieSorting | Medium | 100% | 50.6% | ||
| #1233 | Remove Sub-Folders from the Filesystem ArrayStringDepth-First SearchTrie | Medium | 88% | 78.6% | ||
| #336 | Palindrome Pairs ArrayHash TableStringTrieHash Function | Hard | 88% | 37.4% | ||
| #3042 | Count Prefix and Suffix Pairs I ArrayStringTrieRolling HashString MatchingHash Function | Easy | 100% | 77.8% | ||
| #440 | Hard | 100% | 46.4% | |||
| #1948 | Delete Duplicate Folders in System ArrayHash TableStringDepth-First SearchTrieSortingHash Function | Hard | 88% | 77.4% | ||
| #386 | Lexicographical Numbers Depth-First SearchTrie | Medium | 53% | 76.3% | ||
| #527 | Word Abbreviation ArrayStringGreedyTrieSorting | Hard | 88% | 0.6% | ||
| #421 | Maximum XOR of Two Numbers in an Array ArrayHash TableBit ManipulationTrie | Medium | 38% | 53.6% | ||
| #3045 | Count Prefix and Suffix Pairs II ArrayStringTrieRolling HashString MatchingHash FunctionZ Algorithm | Hard | 100% | 28.7% | ||
| #1698 | Number of Distinct Substrings in a String StringTrieRolling HashSuffix ArrayHash Function | Medium | 100% | 64.7% | ||
| #616 | Add Bold Tag in String ArrayHash TableStringTrieString MatchingAho–Corasick Algorithm | Medium | 78% | 51.4% | ||
| #720 | Longest Word in Dictionary ArrayHash TableStringTrieSorting | Medium | 75% | 55.1% | ||
| #1032 | Stream of Characters ArrayStringDesignTrieData StreamAho–Corasick Algorithm | Hard | 63% | 52.6% | ||
| #2977 | Minimum Cost to Convert String II ArrayStringDynamic ProgrammingGraph TheoryTrieShortest Path | Hard | 63% | 59.6% | ||
| #648 | Replace Words ArrayHash TableStringTrie | Medium | 52% | 68.9% | ||
| #2452 | Words Within Two Edits of Dictionary ArrayStringTrie | Medium | 25% | 73.4% | ||
| #3076 | Shortest Uncommon Substring in an Array ArrayHash TableStringTrie | Medium | 100% | 51.1% | ||
| #2416 | Sum of Prefix Scores of Strings ArrayStringTrieCounting | Hard | 100% | 60.8% | ||
| #2227 | Encrypt and Decrypt Strings ArrayHash TableStringDesignTrie | Hard | 100% | 38.7% | ||
| #677 | Map Sum Pairs Hash TableStringDesignTrie | Medium | 100% | 57.3% | ||
| #472 | Concatenated Words ArrayStringDynamic ProgrammingDepth-First SearchTrieSorting | Hard | 53% | 49.9% | ||
| #2261 | K Divisible Elements Subarrays ArrayHash TableTrieRolling HashHash FunctionEnumeration | Medium | 52% | 55.1% | ||
| #745 | Prefix and Suffix Search ArrayHash TableStringDesignTrie | Hard | 25% | 41.0% | ||
| #2707 | Extra Characters in a String ArrayHash TableStringDynamic ProgrammingTrie | Medium | 15% | 57.4% | ||
| #1023 | Camelcase Matching ArrayTwo PointersStringTrieString Matching | Medium | 75% | 65.6% | ||
| #676 | Implement Magic Dictionary Hash TableStringDepth-First SearchDesignTrie | Medium | 45% | 58.0% | ||
| #3093 | Longest Common Suffix Queries ArrayStringTrie | Hard | 25% | 52.6% | ||
| #1804 | Implement Trie II (Prefix Tree) Hash TableStringDesignTrie | Medium | 13% | 63.5% | ||
| #2932 | Maximum Strong Pair XOR I ArrayHash TableBit ManipulationTrieSliding Window | Easy | 100% | 76.3% | ||
| #2935 | Maximum Strong Pair XOR II ArrayHash TableBit ManipulationTrieSliding Window | Hard | 100% | 33.2% | ||
| #1803 | Count Pairs With XOR in a Range ArrayBit ManipulationTrie | Hard | 100% | 46.5% | ||
| #1178 | Number of Valid Words for Each Puzzle ArrayHash TableStringBit ManipulationTrie | Hard | 100% | 47.9% | ||
| #820 | Short Encoding of Words ArrayHash TableStringTrie | Medium | 30% | 60.9% | ||
| #1065 | Index Pairs of a String ArrayStringTrieSortingAho–Corasick Algorithm | Easy | 25% | 68.7% | ||
| #1707 | Maximum XOR With an Element From Array ArrayBit ManipulationTrie | Hard | 25% | 58.9% | ||
| #3597 | Partition String Hash TableStringTrieSimulation | Medium | 25% | 59.4% | ||
| #1316 | Distinct Echo Substrings StringTrieRolling HashSuffix ArrayHash FunctionSuffix AutomatonSuffix Tree | Hard | 25% | 53.3% | ||
| #425 | Word Squares ArrayStringBacktrackingTrie | Hard | 25% | 54.7% | ||
| #758 | Bold Words in String ArrayHash TableStringTrieString MatchingAho–Corasick Algorithm | Medium | 25% | 52.5% | ||
| #1858 | Longest Word With All Prefixes ArrayStringDepth-First SearchTrie | Medium | 25% | 72.1% |
Showing 53 of 53 problems in Trie (Prefix Tree)Filtered: All Companies