Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a word into the Trie.
DSA C#
public void Insert(string word) {
TrieNode node = root;
foreach (char c in word) {
if (!node.Children.ContainsKey(c)) {
node.Children.Add(c, new TrieNode());
}
node = node.[1];
}
node.IsWord = true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Trying to add a new child node again instead of moving to existing child.
Using ContainsKey instead of accessing the child node.
✗ Incorrect
We move to the child node corresponding to character c by accessing node.Children[c].
2fill in blank
mediumComplete the code to check if a prefix exists in the Trie.
DSA C#
public bool StartsWith(string prefix) {
TrieNode node = root;
foreach (char c in prefix) {
if (!node.Children.ContainsKey(c)) {
return false;
}
node = node.[1];
}
return true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using ContainsKey instead of accessing the child node.
Trying to add new nodes while searching.
✗ Incorrect
To move down the Trie, we access the child node for character c using node.Children[c].
3fill in blank
hardFix the error in the search method to correctly check if a word exists in the Trie.
DSA C#
public bool Search(string word) {
TrieNode node = root;
foreach (char c in word) {
if (!node.Children.ContainsKey(c)) {
return false;
}
node = node.[1];
}
return node.IsWord;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using ContainsKey instead of accessing the child node.
Adding new nodes during search.
✗ Incorrect
We must move to the child node for each character using node.Children[c] to continue the search.
4fill in blank
hardFill both blanks to complete the TrieNode class constructor and initialize the children dictionary.
DSA C#
public class TrieNode { public Dictionary<char, TrieNode> Children; public bool IsWord; public TrieNode() { Children = new Dictionary<char, [1]>(); IsWord = [2]; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using bool as dictionary value type.
Setting IsWord to true in constructor.
✗ Incorrect
Children is a dictionary mapping characters to TrieNode objects, and IsWord starts as false.
5fill in blank
hardFill all three blanks to complete the method that returns all words in the Trie starting with a given prefix.
DSA C#
public List<string> GetWordsWithPrefix(string prefix) {
List<string> results = new List<string>();
TrieNode node = root;
foreach (char c in prefix) {
if (!node.Children.ContainsKey(c)) {
return results;
}
node = node.[1];
}
DFS(node, prefix, results);
return results;
}
private void DFS(TrieNode node, string word, List<string> results) {
if (node.IsWord) {
results.Add(word);
}
foreach (var pair in node.Children) {
DFS(pair.[2], word + pair.[3], results);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using pair.Key as node instead of pair.Value.
Appending pair.Value instead of pair.Key to word.
✗ Incorrect
We move to child node with Children[c], then in DFS use pair.Value for node and pair.Key for character.
