Bird
Raised Fist0
DSA Javascriptprogramming~20 mins

Trie vs Hash Map for Prefix Matching in DSA Javascript - Compare & Choose

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Prefix Matching Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of Prefix Search Using Trie
What is the output of the following JavaScript code that uses a Trie to find words with a given prefix?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = {};
    this.isWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children[char]) {
        node.children[char] = new TrieNode();
      }
      node = node.children[char];
    }
    node.isWord = true;
  }

  startsWith(prefix) {
    let node = this.root;
    for (const char of prefix) {
      if (!node.children[char]) {
        return [];
      }
      node = node.children[char];
    }
    const results = [];
    const dfs = (currNode, path) => {
      if (currNode.isWord) {
        results.push(path);
      }
      for (const c in currNode.children) {
        dfs(currNode.children[c], path + c);
      }
    };
    dfs(node, prefix);
    return results;
  }
}

const trie = new Trie();
['cat', 'car', 'cart', 'dog', 'dove'].forEach(word => trie.insert(word));
console.log(trie.startsWith('car'));
A["car", "cart"]
B["cat", "car", "cart"]
C[]
D["cart"]
Attempts:
2 left
💡 Hint
Think about which words start exactly with the prefix 'car'.
🧠 Conceptual
intermediate
1:30remaining
Why Use Trie Over Hash Map for Prefix Matching?
Which of the following is the main advantage of using a Trie over a Hash Map for prefix matching?
AHash Map can store duplicate keys which Trie cannot.
BHash Map uses less memory than Trie for storing prefixes.
CTrie allows efficient prefix search without checking every key explicitly.
DTrie requires less code to implement than Hash Map.
Attempts:
2 left
💡 Hint
Consider how prefix search works in both data structures.
❓ Predict Output
advanced
2:00remaining
Output of Prefix Search Using Hash Map
What is the output of the following JavaScript code that uses a Hash Map (object) to find words with a given prefix?
DSA Javascript
const words = ['apple', 'app', 'apricot', 'banana', 'bat'];
const wordMap = {};
words.forEach(word => { wordMap[word] = true; });

function findPrefix(prefix) {
  const results = [];
  for (const word in wordMap) {
    if (word.startsWith(prefix)) {
      results.push(word);
    }
  }
  return results;
}

console.log(findPrefix('ap'));
A["apple", "app", "apricot"]
B["apple", "app"]
C["apricot"]
D[]
Attempts:
2 left
💡 Hint
Check which words start with 'ap'.
🔧 Debug
advanced
2:00remaining
Identify the Error in Trie Insertion
What error will the following code produce when inserting words into a Trie?
DSA Javascript
class TrieNode {
  constructor() {
    this.children = new Map();
    this.isWord = false;
  }
}

class Trie {
  constructor() {
    this.root = new TrieNode();
  }

  insert(word) {
    let node = this.root;
    for (const char of word) {
      if (!node.children.get(char)) {
        node.children.set(char, new TrieNode());
      }
      node = node.children.get(char);
    }
    node.isWord = true;
  }
}

const trie = new Trie();
trie.insert('hello');
ATypeError: node.children[char] is not a function
BSyntaxError: Unexpected token
CNo error, code runs correctly
DTypeError: node.children[char] is undefined
Attempts:
2 left
💡 Hint
Check how children are accessed when children is a Map.
🧠 Conceptual
expert
2:30remaining
Time Complexity Comparison for Prefix Search
Which statement correctly compares the time complexity of prefix search in a Trie versus a Hash Map storing N words each of average length L?
ATrie prefix search is O(1), Hash Map prefix search is O(L)
BTrie prefix search is O(L), Hash Map prefix search is O(N * L)
CTrie prefix search is O(N), Hash Map prefix search is O(L)
DBoth Trie and Hash Map prefix searches are O(N * L)
Attempts:
2 left
💡 Hint
Consider how many characters and words are checked in each data structure.

Practice

(1/5)
1. Which data structure is generally more efficient for prefix matching in a large set of strings?
easy
A. Linked List, because it allows sequential access
B. Hash Map, because it stores keys with constant time lookup
C. Array, because it stores elements in order
D. Trie, because it stores prefixes explicitly and allows fast prefix search

Solution

  1. Step 1: Understand prefix matching requirement

    Prefix matching means finding all strings that start with a given prefix efficiently.
  2. 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.
  3. Final Answer:

    Trie, because it stores prefixes explicitly and allows fast prefix search -> Option D
  4. Quick Check:

    Prefix search = Trie [OK]
Hint: Trie stores prefixes explicitly, ideal for prefix search [OK]
Common Mistakes:
  • 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
2. Which of the following is the correct way to check if a prefix exists in a Trie node in JavaScript?
easy
A. if (prefix in trieNode) { ... }
B. if (trieNode.hasOwnProperty(prefix)) { ... }
C. if (trieNode[prefix]) { ... }
D. if (trieNode.contains(prefix)) { ... }

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    if (prefix in trieNode) { ... } -> Option A
  4. Quick Check:

    Use 'in' operator to check keys [OK]
Hint: Use 'in' operator to check keys in objects [OK]
Common Mistakes:
  • Using non-existent 'contains' method
  • Checking property truthiness instead of existence
  • Confusing hasOwnProperty with 'in' operator
3. What will be the output of the following code snippet?
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);
medium
A. true true true true
B. true true false undefined
C. true false false undefined
D. false false false undefined

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    true true true true -> Option A
  4. Quick Check:

    All keys and isEnd exist as expected [OK]
Hint: Trace each insertion step-by-step [OK]
Common Mistakes:
  • Assuming 't' node missing after insertions
  • Confusing isEnd property placement
  • Not updating node reference inside loop
4. The following code attempts to check if a prefix exists in a Trie but does not work correctly. What is the bug?
function startsWith(trie, prefix) {
  let node = trie;
  for (const char of prefix) {
    if (!node[char]) return false;
    node = node[char];
  }
  return true;
}
medium
A. It incorrectly returns false if a node exists but is falsy
B. It does not check if the prefix is a complete word
C. It should use 'char in node' instead of '!node[char]'
D. It does not handle empty prefix input

Solution

  1. 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.
  2. Step 2: Suggest correct key existence check

    Using 'char in node' correctly checks if the key exists regardless of value truthiness.
  3. Final Answer:

    It should use 'char in node' instead of '!node[char]' -> Option C
  4. Quick Check:

    Use 'in' operator to check keys, not truthiness [OK]
Hint: Check key existence with 'in', not truthiness [OK]
Common Mistakes:
  • Using falsy check instead of key existence
  • Confusing prefix existence with complete word check
  • Ignoring empty prefix edge case
5. You want to implement a prefix search that returns all words starting with a given prefix from a large dictionary. Which approach is best and why?
// 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
hard
A. Approach 4, because binary search on sorted array quickly finds prefix range
B. Approach 2, because Trie allows efficient prefix traversal and retrieval
C. Approach 3, because filtering arrays is simple and fast for large data
D. Approach 1, because Hash Map has constant time lookup for prefixes

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    Approach 2, because Trie allows efficient prefix traversal and retrieval -> Option B
  4. Quick Check:

    Prefix search efficiency = Trie [OK]
Hint: Trie stores prefixes explicitly, best for prefix search [OK]
Common Mistakes:
  • Assuming hash map supports prefix search
  • Ignoring performance cost of filtering large arrays
  • Overestimating binary search for prefix retrieval
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard