Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a word into the Trie.
DSA Python
def insert_word(root, word): node = 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
Attempts:
3 left
💡 Hint
Common Mistakes
Using a dictionary or list instead of a TrieNode object.
Not creating a new node when the character is missing.
✗ Incorrect
We create a new TrieNode object for each new character path in the Trie.
2fill in blank
mediumComplete the code to search for a word in the Trie.
DSA Python
def search_word(root, word): node = root for char in word: if char not in node.children: return False node = node.children[[1]] return node.is_end_of_word
Attempts:
3 left
💡 Hint
Common Mistakes
Using the whole word or wrong variable to index children.
Using node or root instead of the character.
✗ Incorrect
We use the current character 'char' to move down the Trie nodes.
3fill in blank
hardFix the error in the TrieNode class constructor to initialize children correctly.
DSA Python
class TrieNode: def __init__(self): self.children = [1] self.is_end_of_word = False
Attempts:
3 left
💡 Hint
Common Mistakes
Using a list or set instead of a dictionary.
Setting children to None which causes errors when accessing.
✗ Incorrect
Children should be a dictionary to map characters to TrieNode children.
4fill in blank
hardFill both blanks to implement a function that checks if any word in the Trie starts with a given prefix.
DSA Python
def starts_with(root, prefix): node = root for char in prefix: if [1] not in node.children: return False node = node.children[[2]] return True
Attempts:
3 left
💡 Hint
Common Mistakes
Using the whole prefix or wrong variable instead of the character.
Using node or root instead of the character.
✗ Incorrect
We check if each character in prefix exists in children and move down using that character.
5fill in blank
hardFill all three blanks to implement a function that collects all words stored in the Trie.
DSA Python
def collect_words(node, prefix, words): if node.is_end_of_word: words.append([1]) for char, child_node in node.children.items(): collect_words(child_node, prefix [2] [3], words)
Attempts:
3 left
💡 Hint
Common Mistakes
Appending node or child_node instead of prefix.
Using subtraction or wrong operator instead of +.
Not adding the character to prefix during recursion.
✗ Incorrect
We append the current prefix as a word, then recursively add characters to prefix using + operator.
