Home
DSA Patterns
Trie
Prefix Matching
Prefix Matching
Prefix Matching: use Trie to efficiently find all keys matching a prefix.
Problem Understanding
This is essentially startsWith but often implies retrieving related data or completing the word. In this lesson, we use the standard startsWith logic as the core building block for Autocomplete systems.
Algorithm Strategy
- Start at the
Trieroot. - Iterate through each character of the
prefix. - Check if the current node has a child for that character.
- If No: Prefix doesn't exist. Return
False. - If Yes: Move to that child node.
- If loop completes: The path exists. Return
True(unlike Search, we ignoreisEnd).
Interactive Visualization
PREFIX "ap" · GREEN = END OF A STORED WORD
TRIE BUILT
Checked
0
Depth
0
Returns
:
The trie holds "apple", "apply", "apt", "bat"
Next
startsWith("ap"): start at the root
Words
Prefix
See how startsWith confirms if a path exists without requiring the isEnd flag.
Dry Run: startsWith('ap')
Trie has 'apple'.
| Char | Child Exists? | Action |
|---|---|---|
| 'a' | Yes | Move to 'a'. |
| 'p' | Yes | Move to 'p'. |
| End | - | Loop done. Path exists. Return True. |
Edge Cases & Checks
Important checks:
No Matches: Return valid value (false/empty list).
Empty Prefix: Matches every stored word: the loop never runs and
startsWithreturns true.Case: Ensure 'A' doesn't match 'a' without normalization.
Solution (StartsWith Logic)
O(L) Time.
Prefix Matching Code
1Trie.prototype.startsWith = function(prefix) {2 let node = this;3 for(const char of prefix) {4 if(!node.children[char]) return false;5 node = node.children[char];6 }7 return true;8};
Prefix Matching in Python, Java, C++, TypeScript and C
Prefix Matching in Python
def startsWith(self, prefix: str) -> bool:
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return TruePrefix Matching in Java
public boolean startsWith(String prefix) {
TrieNode node = root;
for(char c : prefix.toCharArray()) {
int idx = c - 'a';
if(node.children[idx] == null) return false;
node = node.children[idx];
}
return true;
}Prefix Matching in C++
bool startsWith(string prefix) {
TrieNode* node = root;
for(char c : prefix) {
int idx = c - 'a';
if(!node->children[idx]) return false;
node = node->children[idx];
}
return true;
}Prefix Matching in TypeScript
startsWith(prefix: string): boolean {
let node: Trie = this;
for (const char of prefix) {
if (!node.children[char]) return false;
node = node.children[char];
}
return true;
}Prefix Matching in C
bool trieStartsWith(Trie* obj, char * prefix) {
Trie* node = obj;
for(int i=0; prefix[i] != '\0'; i++) {
int idx = prefix[i] - 'a';
if(node->children[idx] == NULL) return false;
node = node->children[idx];
}
return true;
}More practice: DSA interview questions with answers · patterns cheat sheet
