Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to insert a word into the Trie.
DSA Java
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (!node.children.containsKey(c)) {
node.children.put(c, new TrieNode());
}
node = node.children[1];
}
node.isWord = true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using node.get(c) instead of node.children.get(c).
Trying to access children with square brackets like an array.
Calling get() without arguments.
✗ Incorrect
We must move to the child node corresponding to character c by accessing node.children.get(c).
2fill in blank
mediumComplete the code to check if a prefix exists in the Trie.
DSA Java
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
if (!node.children.containsKey(c)) {
return false;
}
node = node.children[1];
}
return true;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using square brackets to access children.
Using contains instead of get.
Calling get without arguments.
✗ Incorrect
To move to the next node, we use node.children.get(c) to get the child node for character c.
3fill in blank
hardFix the error in the HashMap prefix search method to return true if any key starts with the prefix.
DSA Java
public boolean startsWithPrefix(HashMap<String, Integer> map, String prefix) {
for (String key : map.keySet()) {
if (key[1](prefix)) {
return true;
}
}
return false;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using contains which checks anywhere in the string.
Using equals which checks exact match.
Using endsWith which checks the end of the string.
✗ Incorrect
The String method startsWith checks if the key begins with the given prefix.
4fill in blank
hardFill both blanks to create a TrieNode class with a children map and a boolean flag.
DSA Java
class TrieNode { Map<Character, TrieNode> children = new HashMap<>(); boolean [1]; public TrieNode() { this.[2] = false; } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using isPrefix which is less common and confusing.
Using hasChild which is not a boolean flag for word end.
Using isEnd which is valid but not used here.
✗ Incorrect
The boolean flag is commonly named isWord to mark the end of a word in the Trie.
5fill in blank
hardFill the blanks to implement a method that counts words with a given prefix using a HashMap.
DSA Java
public int countPrefixWords(HashMap<String, Integer> map, String prefix) {
int count = 0;
for (String key : map.keySet()) {
if (key[1](prefix)) {
count [2] map.get(key);
}
}
return count;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using contains instead of startsWith for prefix check.
Using -= instead of += for counting.
Using contains in the if condition which is incorrect here.
✗ Incorrect
We check if the key starts with the prefix, then add the value from the map to count. The contains method is a distractor here.
