Trie vs Hash Map for Prefix Matching in DSA Javascript - Complexity Comparison
We want to compare how fast tries and hash maps find words starting with a prefix.
How does the time to find matches grow as we add more words or longer prefixes?
Analyze the time complexity of prefix search using a trie and a hash map.
// Trie prefix search
function trieSearch(root, prefix) {
let node = root;
for (const char of prefix) {
if (!node.children[char]) return [];
node = node.children[char];
}
return collectWords(node);
}
// Hash map prefix search
function hashMapSearch(words, prefix) {
return words.filter(word => word.startsWith(prefix));
}
The trie search walks down nodes for each prefix letter. The hash map search checks every word.
Look at what repeats most in each method.
- Trie search primary operation: Loop over prefix letters to go down trie nodes.
- Trie search times: Once per prefix letter (length m).
- Hash map search primary operation: Loop over all words to check prefix.
- Hash map search times: Once per word (n words), each check up to prefix length m.
How does work grow as input grows?
| Input Size (n words) | Trie Search (prefix length m=3) | Hash Map Search (prefix length m=3) |
|---|---|---|
| 10 | 3 steps down trie | 10 words x 3 chars = 30 checks |
| 100 | 3 steps down trie | 100 words x 3 chars = 300 checks |
| 1000 | 3 steps down trie | 1000 words x 3 chars = 3000 checks |
Trie search time depends only on prefix length, stays small as words grow.
Hash map search time grows linearly with number of words times prefix length.
Time Complexity: O(m) for trie search, O(n x m) for hash map search
Trie search time grows with prefix length only, hash map search grows with total words and prefix length.
[X] Wrong: "Hash map search is always faster because hash maps are quick."
[OK] Correct: Hash maps are fast for exact keys, but prefix search needs checking many words, so it slows down as word list grows.
Understanding these differences helps you choose the right tool for prefix search tasks in real projects.
What if we stored all prefixes in the hash map as keys? How would that change the time complexity?
Practice
Solution
Step 1: Understand prefix matching requirement
Prefix matching means finding all strings that start with a given prefix efficiently.Step 2: Compare Trie and Hash Map for prefix search
Trie stores prefixes explicitly, allowing quick traversal to all words with that prefix. Hash Map does not store prefixes, so it requires checking all keys or additional structures.Final Answer:
Trie, because it stores prefixes explicitly and allows fast prefix search -> Option DQuick Check:
Prefix search = Trie [OK]
- Thinking hash map can do prefix search directly
- Confusing prefix matching with exact key lookup
- Assuming arrays or linked lists are efficient for prefix search
Solution
Step 1: Understand how to check keys in JavaScript objects
The 'in' operator checks if a property exists in an object or its prototype chain.Step 2: Compare options for checking prefix in Trie node
if (prefix in trieNode) { ... } uses 'prefix in trieNode', which correctly checks if the prefix key exists. if (trieNode.hasOwnProperty(prefix)) { ... } uses hasOwnProperty which is valid but less common for prefix check. if (trieNode[prefix]) { ... } checks truthiness which can fail if value is falsy. if (trieNode.contains(prefix)) { ... } uses a non-existent method.Final Answer:
if (prefix in trieNode) { ... } -> Option AQuick Check:
Use 'in' operator to check keys [OK]
- Using non-existent 'contains' method
- Checking property truthiness instead of existence
- Confusing hasOwnProperty with 'in' operator
const trie = {};
function insert(word) {
let node = trie;
for (const char of word) {
if (!(char in node)) node[char] = {};
node = node[char];
}
node.isEnd = true;
}
insert('cat');
insert('car');
insert('dog');
console.log('c' in trie, 'a' in trie['c'], 't' in trie['c']['a'], trie['c']['a']['t'].isEnd);Solution
Step 1: Trace insertions of words into the trie
Inserting 'cat' creates nodes c -> a -> t with isEnd true at 't'. Inserting 'car' adds r under c -> a. Inserting 'dog' adds d -> o -> g separately.Step 2: Check existence of keys and isEnd property
'c' exists in trie, 'a' exists under 'c', 't' exists under 'a', and 't' node has isEnd true from 'cat' insertion.Final Answer:
true true true true -> Option AQuick Check:
All keys and isEnd exist as expected [OK]
- Assuming 't' node missing after insertions
- Confusing isEnd property placement
- Not updating node reference inside loop
function startsWith(trie, prefix) {
let node = trie;
for (const char of prefix) {
if (!node[char]) return false;
node = node[char];
}
return true;
}Solution
Step 1: Analyze the condition '!node[char]'
This condition fails if node[char] exists but is falsy (like an empty object or false), causing incorrect false return.Step 2: Suggest correct key existence check
Using 'char in node' correctly checks if the key exists regardless of value truthiness.Final Answer:
It should use 'char in node' instead of '!node[char]' -> Option CQuick Check:
Use 'in' operator to check keys, not truthiness [OK]
- Using falsy check instead of key existence
- Confusing prefix existence with complete word check
- Ignoring empty prefix edge case
// Approach 1: Use a Hash Map storing all words as keys // Approach 2: Use a Trie storing words character by character // Approach 3: Use an array and filter words by prefix // Approach 4: Use a sorted array and binary search for prefix
Solution
Step 1: Evaluate each approach for prefix search
Hash Map (Approach 1) cannot do prefix search efficiently as keys are exact. Array filter (Approach 3) is slow for large data. Sorted array with binary search (Approach 4) helps but retrieving all matches requires scanning range.Step 2: Understand Trie advantages
Trie (Approach 2) stores prefixes explicitly, allowing fast traversal to all words sharing the prefix, making it best for prefix search in large datasets.Final Answer:
Approach 2, because Trie allows efficient prefix traversal and retrieval -> Option BQuick Check:
Prefix search efficiency = Trie [OK]
- Assuming hash map supports prefix search
- Ignoring performance cost of filtering large arrays
- Overestimating binary search for prefix retrieval
Ready to prove it?
Pass the test and this pattern moves unknown
