Complete the code to insert a word into the Trie.
def insert(self, word): node = self.root for char in word: if char not in node.children: node.children[char] = [1]() node = node.children[char] node.is_end_of_word = True
We create a new TrieNode object for each new character path.
Complete the code to check if a prefix exists in the Trie.
def starts_with(self, prefix): node = self.root for char in prefix: if char not in node.children: return [1] node = node.children[char] return True
If any character is missing, the prefix does not exist, so return False.
Fix the error in the search method to correctly find a word in the Trie.
def search(self, word): node = self.root for char in word: if char not in node.children: return False node = node.children[[1]] return node.is_end_of_word
We must use the current character 'char' to move to the next node.
Fill both blanks to collect all words starting with a prefix using DFS.
def dfs(self, node, prefix, results): if node.is_end_of_word: results.append(prefix) for [1], child_node in node.children.items(): self.dfs(child_node, prefix + [2], results)
We use 'char' as the key and add it to prefix to explore deeper.
Fill all three blanks to implement the autocomplete method returning all words with given prefix.
def autocomplete(self, prefix): node = self.root for [1] in prefix: if [2] not in node.children: return [] node = node.children[[3]] results = [] self.dfs(node, prefix, results) return results
Use 'char' to iterate and check children keys to find the node for prefix.
