Home
DSA Patterns
Trie
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
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};
