Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a new Trie node.
DSA C
struct TrieNode* createNode() {
struct TrieNode* node = (struct TrieNode*)malloc(sizeof(struct TrieNode));
node->isEndOfWord = [1];
for (int i = 0; i < 26; i++) {
node->children[i] = NULL;
}
return node;
}Attempts:
3 left
💡 Hint
Common Mistakes
Setting isEndOfWord to 1 by mistake.
Using NULL instead of 0 for a boolean flag.
✗ Incorrect
The isEndOfWord flag should be initialized to 0 (false) when creating a new Trie node.
2fill in blank
mediumComplete the code to insert a word into the Trie.
DSA C
void insert(struct TrieNode* root, const char* word) {
struct TrieNode* current = root;
for (int i = 0; word[i] != '\0'; i++) {
int index = word[i] - 'a';
if (current->children[[1]] == NULL) {
current->children[index] = createNode();
}
current = current->children[index];
}
current->isEndOfWord = 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i instead of index to access children.
Using word[i] directly as an index.
✗ Incorrect
We use the calculated index to access the children array for the current character.
3fill in blank
hardFix the error in the search function to correctly check if a word exists in the Trie.
DSA C
int search(struct TrieNode* root, const char* word) {
struct TrieNode* current = root;
for (int i = 0; word[i] != '\0'; i++) {
int index = word[i] - 'a';
if (current->children[index] == NULL) {
return 0;
}
current = current->children[[1]];
}
return current->isEndOfWord;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i instead of index to access children.
Using word[i] directly as an index.
✗ Incorrect
We must use the index variable to move to the next child node corresponding to the current character.
4fill in blank
hardFill both blanks to implement a function that checks if any word in the Trie starts with a given prefix.
DSA C
int startsWith(struct TrieNode* root, const char* prefix) {
struct TrieNode* current = root;
for (int i = 0; prefix[i] != '\0'; i++) {
int index = prefix[i] - 'a';
if (current->children[[1]] == NULL) {
return 0;
}
current = current->children[[2]];
}
return 1;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using i instead of index in one or both blanks.
Using prefix[i] directly as an index.
✗ Incorrect
Both blanks should use the index variable to correctly traverse the Trie nodes for the prefix characters.
5fill in blank
hardFill all three blanks to implement a function that deletes the Trie and frees memory.
DSA C
void freeTrie(struct TrieNode* root) {
if (root == NULL) return;
for (int i = 0; i < [1]; i++) {
if (root->children[[2]] != NULL) {
freeTrie(root->children[[3]]);
}
}
free(root);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using 0 or root instead of the loop variable to access children.
Not looping through all 26 children.
✗ Incorrect
We loop through all 26 children using index i, and recursively free each child node before freeing the root.
