Complete the code to insert a word into the Trie.
insert(word) {
let node = this.root;
for (let char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.[1];
}
node.isEnd = true;
}We move to the child node corresponding to the current character using children.get(char).
Complete the code to check if a word exists in the Trie.
search(word) {
let node = this.root;
for (let char of word) {
if (!node.children.has(char)) {
return false;
}
node = node.children.get(char);
}
return node[1];
}The isEnd property tells if the node marks the end of a valid word.
Fix the error in the DFS function to find the longest word built one character at a time.
dfs(node, path) {
if (!node.isEnd && node !== this.root) return;
if (path.length > this.longest.length) {
this.longest = path;
}
for (let [char, child] of node.children) {
this.dfs(child, path + [1]);
}
}We add the character char to the current path string during DFS.
Fill both blanks to complete the reduce function that builds an object filtering words with length greater than 3 and mapping them to their lengths.
const result = words.reduce((acc, word) => {
if (word.length [2] 3) {
acc[word][1] word.length;
}
return acc;
}, {});The equals sign = assigns the length as the value for the word key in the accumulator object, and > filters words longer than 3.
Fill all three blanks to complete the function that finds the longest word in the dictionary using Trie and DFS.
function longestWord(words) {
const trie = new Trie();
for (const word of words) {
trie.[1](word);
}
trie.longest = "";
trie.[2](trie.root, "");
return trie.[3];
}Insert words into the Trie, run DFS to find the longest word, then return the longest word.