3. Given the following TypeScript code snippet for inserting words into a Trie and searching for prefix suggestions, what will be the output of
autocomplete.getSuggestions('ca')?
class TrieNode {
children: Map = new Map();
isEnd: boolean = false;
}
class AutocompleteSystem {
root: TrieNode = new TrieNode();
insert(word: string) {
let node = this.root;
for (const char of word) {
if (!node.children.has(char)) {
node.children.set(char, new TrieNode());
}
node = node.children.get(char)!;
}
node.isEnd = true;
}
getSuggestions(prefix: string): string[] {
let node = this.root;
for (const char of prefix) {
if (!node.children.has(char)) return [];
node = node.children.get(char)!;
}
const results: string[] = [];
const dfs = (currNode: TrieNode, path: string) => {
if (currNode.isEnd) results.push(path);
for (const [ch, nextNode] of currNode.children) {
dfs(nextNode, path + ch);
}
};
dfs(node, prefix);
return results;
}
}
const autocomplete = new AutocompleteSystem();
autocomplete.insert('cat');
autocomplete.insert('car');
autocomplete.insert('cap');
autocomplete.insert('dog');
console.log(autocomplete.getSuggestions('ca'));