Complete the code to insert a word into the Trie.
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;
}Each node's children is a Map to store next characters and their nodes. So we create a new Map for a new child.
Complete the code to check if a prefix exists in the Trie.
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;
}We check if the current node's children has the current character from the prefix.
Fix the error in the Hash Map prefix search function to correctly check prefixes.
function hashMapStartsWith(map, prefix) {
for (let key of map.keys()) {
if (key[1]prefix) {
return true;
}
}
return false;
}To check if a key starts with the prefix, use the startsWith method.
Fill both blanks to create a Trie node and mark the end of a word.
function createNode() {
return {
children: [1],
isEnd: [2]
};
}A Trie node has children as a Map and isEnd initially false.
Fill all three blanks to build a Hash Map from words and check prefix existence.
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;
}We store true for each word in the map. To check prefix, use startsWith and return true if found.