Trie vs Hash Map for Prefix Matching in DSA Typescript - Complexity Comparison
We want to understand how fast we can find words that start with a certain prefix using two common data structures.
Which one works better as the list of words grows?
Analyze the time complexity of prefix search using Trie and Hash Map.
// Trie prefix search
function trieStartsWith(root: TrieNode, prefix: string): boolean {
let node = root;
for (const char of prefix) {
if (!node.children.has(char)) return false;
node = node.children.get(char)!;
}
return true;
}
// Hash Map prefix search
function hashMapStartsWith(words: string[], prefix: string): boolean {
for (const word of words) {
if (word.startsWith(prefix)) return true;
}
return false;
}
The first checks prefix by walking down the Trie nodes. The second checks each word in the list one by one.
Look at what repeats most in each method.
- Trie: Loop over prefix characters once.
- Hash Map: Loop over all words, then loop over prefix characters inside startsWith.
- Dominant operation: Hash Map loops over all words, which grows with number of words.
Compare how work grows as we add more words or longer prefixes.
| Input Size (words n) | Trie Operations | Hash Map Operations |
|---|---|---|
| 10 | Check prefix length (m) steps, e.g. 3 | Check up to 10 words * prefix length |
| 100 | Still check prefix length (m) steps | Check up to 100 words * prefix length |
| 1000 | Still check prefix length (m) steps | Check up to 1000 words * prefix length |
Pattern observation: Trie time depends mostly on prefix length, not number of words. Hash Map time grows with number of words.
Time Complexity: O(m) for Trie, O(n * m) for Hash Map
Trie searches quickly by prefix length only. Hash Map checks every word, so it gets slower as word list grows.
[X] Wrong: "Hash Map prefix search is always faster because hash lookups are quick."
[OK] Correct: Hash Map here stores full words, so prefix search still checks many words one by one, making it slower as list grows.
Understanding these differences helps you choose the right tool for prefix search tasks, a common problem in coding interviews and real apps.
What if we stored all prefixes in the Hash Map instead of full words? How would that change the time complexity?
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
