What if you could find all words starting with 'Sam' instantly, no matter how big your list is?
Trie vs Hash Map for Prefix Matching in DSA Typescript - Why the Distinction Matters
Imagine you have a huge phone book and want to find all contacts starting with 'Sam'. You try to look through every name one by one to find matches.
Going through every name manually is slow and tiring. It's easy to miss some matches or take too long, especially if the list is very big.
A Trie organizes words by their letters, so you can quickly jump to all names starting with 'Sam' without checking every single name. It's like having a smart index that guides you straight to the matches.
const contacts = ['Sam', 'Samantha', 'Samuel', 'Sara']; const results = contacts.filter(name => name.startsWith('Sam')); console.log(results);
class TrieNode { children: Map<string, TrieNode> = new Map(); isEndOfWord: boolean = false; } class Trie { root = new TrieNode(); insert(word: string) { /* insert logic */ } startsWith(prefix: string): string[] { /* prefix search logic */ } } const trie = new Trie(); ['Sam', 'Samantha', 'Samuel', 'Sara'].forEach(name => trie.insert(name)); console.log(trie.startsWith('Sam'));
It enables lightning-fast prefix searches even in huge lists, making autocomplete and search features smooth and instant.
When you type in a search box on your phone, the app quickly suggests words starting with what you typed, thanks to Tries organizing the dictionary behind the scenes.
Manual search checks every item, which is slow for big data.
Trie structures group words by letters for fast prefix lookup.
Using Tries makes autocomplete and prefix matching efficient and scalable.
Practice
Solution
Step 1: Understand prefix matching requirements
Prefix matching means finding all strings that start with a given prefix efficiently.Step 2: Compare Trie and Hash Map for prefix queries
Trie stores prefixes explicitly in its structure, allowing quick traversal to all words sharing a prefix. Hash Map only allows exact key lookups, not prefix searches.Final Answer:
Trie, because it stores prefixes explicitly and allows fast prefix queries -> Option AQuick Check:
Prefix matching = Trie [OK]
- Thinking Hash Map supports prefix search efficiently
- Confusing prefix matching with exact key lookup
- Assuming arrays or linked lists are efficient for prefix queries
Solution
Step 1: Identify correct data types for TrieNode properties
Children should map characters (string) to TrieNode objects. isEnd should be boolean to mark word end.Step 2: Check each option's correctness
class TrieNode { children: Map = new Map(); isEnd: boolean = false; } uses Map and boolean isEnd, which is correct. Others use wrong types or incorrect isEnd values.Final Answer:
class TrieNode { children: Map = new Map(); isEnd: boolean = false; } -> Option CQuick Check:
TrieNode children = Map [OK]
- Using array instead of Map for children
- Setting isEnd as number instead of boolean
- Mapping children with wrong key or value types
const map = new Map();
map.set('app', true);
map.set('apple', true);
console.log(map.has('app'));
console.log(map.has('appl'));
Solution
Step 1: Understand Map key lookups
Map.has(key) returns true only if exact key exists. 'app' and 'apple' are keys, 'appl' is not.Step 2: Evaluate console.log outputs
map.has('app') is true; map.has('appl') is false because 'appl' is not a key.Final Answer:
true\nfalse -> Option DQuick Check:
Exact keys only: 'app' true, 'appl' false [OK]
- Assuming map.has supports prefix matching
- Confusing keys 'appl' and 'apple'
- Expecting true for partial keys
insert(word: string) {
let node = this.root;
for (let char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char);
}
node.isEnd = true;
}
What is the main issue causing a runtime error?Solution
Step 1: Analyze node.children.get(char) usage
Even after checking node.children.has(char), node.children.get(char) can theoretically return undefined if the Map is modified concurrently or due to incorrect initialization.Step 2: Identify runtime error cause
Assigning undefined to node causes subsequent property access to fail, leading to runtime error.Final Answer:
node.children.get(char) can return undefined, causing assignment to node to fail -> Option AQuick Check:
Ensure node.children.get(char) is not undefined before assignment [OK]
- Thinking Map.get() returns undefined despite prior has() check
- Overlooking need for root initialization in constructor
- Assuming object-style children access instead of Map methods
// Approach 1: Store all words in a Hash Map and check each key for prefix match // Approach 2: Build a Trie from all words and traverse to prefix node to collect matches
Solution
Step 1: Evaluate Approach 1 (Hash Map with prefix checks)
Hash Map allows O(1) exact lookups but requires checking every key for prefix, which is O(n) and inefficient for large data.Step 2: Evaluate Approach 2 (Trie traversal)
Trie stores prefixes explicitly; traversing to prefix node is O(k) where k is prefix length, then collecting matches is efficient.Step 3: Compare efficiency and scalability
Trie approach scales better for prefix search due to structured prefix storage and avoids scanning all keys.Final Answer:
Approach 2 is better because Trie traversal to prefix node is efficient and collects matches quickly -> Option BQuick Check:
Prefix search = Trie traversal [OK]
- Assuming Hash Map prefix checks are fast
- Ignoring Trie traversal efficiency
- Thinking both approaches perform the same
Ready to prove it?
Pass the test and this pattern moves unknown
