Complete the code to insert a word into the Trie node children.
if (!node.children.has(word[i])) { node.children.set(word[i], new [1]()); }
We create a new TrieNode() as the child node for the current character word[i].
Complete the code to check if a word exists in the Trie.
for (let i = 0; i < word.length; i++) { if (!node.children.has(word[i])) { return false; } node = node.children.get([1])!; } return node.isEndOfWord;
We get the child node corresponding to the current character word[i] to continue traversal.
Fix the error in the code to correctly count how many words start with a given prefix.
function countPrefix(node: TrieNode, prefix: string): number {
for (let i = 0; i < prefix.length; i++) {
if (!node.children.has(prefix[i])) {
return 0;
}
node = node.children.get(prefix[i])!;
}
return [1];
}We return node.count which tracks how many words share this prefix in the Trie.
Fill all three blanks to create a Trie node class with a children map, prefix count, and a boolean flag for word end.
class TrieNode { children: [1]<string, TrieNode>; count: [3]; isEndOfWord: [2]; constructor() { this.children = new Map(); this.count = 0; this.isEndOfWord = false; } }
The children are stored in a Map<string, TrieNode>, count is number for prefix frequency, and isEndOfWord is a boolean flag.
Fill all three blanks to implement a function that inserts a word into the Trie and updates counts.
function insertWord(root: TrieNode, word: string): void {
let node = root;
for (let i = 0; i < word.length; i++) {
if (!node.children.has(word[i])) {
node.children.set(word[i], new [1]());
}
node = node.children.get(word[i])!;
node.[2] += 1;
}
node.[3] = true;
}We create new TrieNode instances, increment the count property on each node, and mark isEndOfWord true at the end.