0
0
DSA Javascriptprogramming~10 mins

Trie vs Hash Map for Prefix Matching in DSA Javascript - Interactive Comparison Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to insert a word into the Trie.

DSA Javascript
function insertWord(root, word) {
  let node = root;
  for (let char of word) {
    if (!node.children.has(char)) {
      node.children.set(char, [1]);
    }
    node = node.children.get(char);
  }
  node.isEnd = true;
}
Drag options to blanks, or click blank then click option'
A{}
Bnew Set()
C[]
Dnew Map()
Attempts:
3 left
💡 Hint
Common Mistakes
Using an array or object instead of Map for children.
Not initializing children for new nodes.
2fill in blank
medium

Complete the code to check if a prefix exists in the Trie.

DSA Javascript
function startsWith(root, prefix) {
  let node = root;
  for (let char of prefix) {
    if (!node.children.has([1])) {
      return false;
    }
    node = node.children.get(char);
  }
  return true;
}
Drag options to blanks, or click blank then click option'
Aprefix
Bnode
Cchar
Droot
Attempts:
3 left
💡 Hint
Common Mistakes
Using the whole prefix instead of the current character.
Using the node or root instead of the character.
3fill in blank
hard

Fix the error in the Hash Map prefix search function to correctly check prefixes.

DSA Javascript
function hashMapStartsWith(map, prefix) {
  for (let key of map.keys()) {
    if (key[1]prefix) {
      return true;
    }
  }
  return false;
}
Drag options to blanks, or click blank then click option'
AendsWith(
BstartsWith(
CindexOf(
Dincludes(
Attempts:
3 left
💡 Hint
Common Mistakes
Using includes or indexOf which check anywhere in the string.
Using endsWith which checks the end of the string.
4fill in blank
hard

Fill both blanks to create a Trie node and mark the end of a word.

DSA Javascript
function createNode() {
  return {
    children: [1],
    isEnd: [2]
  };
}
Drag options to blanks, or click blank then click option'
Anew Map()
Bfalse
Ctrue
D{}
Attempts:
3 left
💡 Hint
Common Mistakes
Setting isEnd to true on creation.
Using an object or array instead of Map for children.
5fill in blank
hard

Fill all three blanks to build a Hash Map from words and check prefix existence.

DSA Javascript
function buildHashMap(words) {
  const map = new Map();
  for (const word of words) {
    map.set(word, [1]);
  }
  return map;
}

function checkPrefix(map, prefix) {
  for (const key of map.keys()) {
    if (key.[2](prefix)) {
      return [3];
    }
  }
  return false;
}
Drag options to blanks, or click blank then click option'
Atrue
BstartsWith
Dfalse
Attempts:
3 left
💡 Hint
Common Mistakes
Returning false instead of true when prefix matches.
Using wrong string method for prefix check.