Bird
Raised Fist0
DSA Cprogramming~20 mins

Trie Insert Operation in DSA C - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Trie Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output after inserting words into a Trie
What is the printed output of the Trie structure after inserting the words "cat", "car", "dog" in order? The output format shows each node's character and its children recursively.
DSA C
typedef struct TrieNode {
    char c;
    struct TrieNode* children[26];
    int isEndOfWord;
} TrieNode;

TrieNode* createNode(char c) {
    TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
    node->c = c;
    node->isEndOfWord = 0;
    for (int i = 0; i < 26; i++) node->children[i] = NULL;
    return node;
}

void insert(TrieNode* root, const char* word) {
    TrieNode* current = root;
    while (*word) {
        int index = *word - 'a';
        if (!current->children[index]) {
            current->children[index] = createNode(*word);
        }
        current = current->children[index];
        word++;
    }
    current->isEndOfWord = 1;
}

void printTrie(TrieNode* root, int level) {
    if (!root) return;
    for (int i = 0; i < 26; i++) {
        if (root->children[i]) {
            for (int j = 0; j < level; j++) printf("  ");
            printf("%c%s\n", root->children[i]->c, root->children[i]->isEndOfWord ? "*" : "");
            printTrie(root->children[i], level + 1);
        }
    }
}

int main() {
    TrieNode* root = createNode(' ');
    insert(root, "cat");
    insert(root, "car");
    insert(root, "dog");
    printTrie(root, 0);
    return 0;
}
A
c
  a
    t
    r*
d
  o
    g*
B
c
  a
    t*
    r*
d
  o
    g*
C
c*
  a
    t
    r
d*
  o
    g
D
c
  a*
    t
    r
d
  o*
    g
Attempts:
2 left
💡 Hint
Look carefully at which nodes mark the end of words with '*'.
🧠 Conceptual
intermediate
1:30remaining
Number of nodes after inserting words in a Trie
After inserting the words "bat", "ball", "bald" into an empty Trie, how many nodes (excluding the root) will the Trie contain?
A6
B9
C8
D7
Attempts:
2 left
💡 Hint
Count shared prefixes only once.
🔧 Debug
advanced
2:00remaining
Identify the error in Trie insertion code
What error will this Trie insertion code produce when inserting the word "apple"? ```c void insert(TrieNode* root, const char* word) { TrieNode* current = root; for (int i = 0; i <= strlen(word); i++) { int index = word[i] - 'a'; if (!current->children[index]) { current->children[index] = createNode(word[i]); } current = current->children[index]; } current->isEndOfWord = 1; } ```
ACompilation error due to missing semicolon
BNo error, code runs correctly and inserts the word
CSegmentation fault due to accessing word[strlen(word)] which is '\0' character
DLogical error: isEndOfWord never set
Attempts:
2 left
💡 Hint
Check the loop boundary and what character is accessed at the end.
❓ Predict Output
advanced
2:00remaining
Output of Trie after inserting and printing words
Given the following insertions into an empty Trie: "to", "tea", "ted", "ten", what is the output of the printTrie function that prints each node's character and marks end of word with '*'?
DSA C
/* Assume same TrieNode and printTrie as in c1 */
int main() {
    TrieNode* root = createNode(' ');
    insert(root, "to");
    insert(root, "tea");
    insert(root, "ted");
    insert(root, "ten");
    printTrie(root, 0);
    return 0;
}
A
t
  o*
  e
    a*
    d*
    n*
B
t
  o*
  e
    a
    d*
    n*
C
t
  o
  e
    a*
    d
    n*
D
t*
  o
  e*
    a
    d
    n
Attempts:
2 left
💡 Hint
Check which nodes mark end of words after insertion.
🧠 Conceptual
expert
1:30remaining
Maximum number of nodes in a Trie after inserting N distinct words of length M
What is the maximum number of nodes in a Trie after inserting N distinct words, each of length M, assuming all words share no common prefix?
AM
BN + M
CN * (M + 1)
DN * M
Attempts:
2 left
💡 Hint
Think about the worst case where no prefixes overlap.

Practice

(1/5)
1. What is the main purpose of the insert operation in a Trie data structure?
easy
A. To add a word character by character into the Trie
B. To delete a word from the Trie
C. To search for a word in the Trie
D. To count the number of words in the Trie

Solution

  1. Step 1: Understand the insert operation

    The insert operation adds each character of a word into the Trie, creating nodes if they don't exist.
  2. Step 2: Differentiate from other operations

    Deleting removes words, searching checks presence, counting totals words. Insert specifically adds words.
  3. Final Answer:

    To add a word character by character into the Trie -> Option A
  4. Quick Check:

    Insert = Add word [OK]
Hint: Insert means adding word letters step-by-step [OK]
Common Mistakes:
  • Confusing insert with search or delete
  • Thinking insert counts words
  • Assuming insert removes words
2. Which of the following is the correct way to declare a Trie node structure in C for insertion?
easy
A. typedef struct TrieNode { char* word; struct TrieNode* children[26]; } TrieNode;
B. typedef struct TrieNode { int data; struct TrieNode* next; } TrieNode;
C. typedef struct TrieNode { struct TrieNode* children[26]; bool isEndOfWord; } TrieNode;
D. typedef struct TrieNode { struct TrieNode* left; struct TrieNode* right; } TrieNode;

Solution

  1. Step 1: Identify Trie node components

    A Trie node has an array of pointers for children (26 letters) and a boolean to mark word end.
  2. Step 2: Match with options

    typedef struct TrieNode { struct TrieNode* children[26]; bool isEndOfWord; } TrieNode; matches this structure. Others describe linked list or binary tree nodes, not Trie nodes.
  3. Final Answer:

    typedef struct TrieNode { struct TrieNode* children[26]; bool isEndOfWord; } TrieNode; -> Option C
  4. Quick Check:

    Trie node = children array + end flag [OK]
Hint: Trie nodes have 26 children pointers and end-of-word flag [OK]
Common Mistakes:
  • Using linked list node structure instead of array
  • Confusing Trie with binary tree node
  • Missing end-of-word boolean
3. What will be the output of the following C code snippet after inserting the word "cat" into an empty Trie and checking the isEndOfWord flag at the last node?
TrieNode* root = createNode();
insert(root, "cat");
bool flag = root->children['c' - 'a']->children['a' - 'a']->children['t' - 'a']->isEndOfWord;
printf("%d", flag);
medium
A. 0
B. Runtime error
C. Compilation error
D. 1

Solution

  1. Step 1: Insert "cat" into Trie

    Each character creates or uses existing nodes. The last character 't' node's isEndOfWord is set to true (1).
  2. Step 2: Check isEndOfWord flag

    Accessing the node for 't' and printing isEndOfWord prints 1 because the word ends there.
  3. Final Answer:

    1 -> Option D
  4. Quick Check:

    Inserted word end flag = 1 [OK]
Hint: End node flag is set to true after insert [OK]
Common Mistakes:
  • Assuming isEndOfWord is 0 after insert
  • Indexing children incorrectly
  • Forgetting to set isEndOfWord during insert
4. Consider the following buggy insert function for a Trie in C:
void insert(TrieNode* root, const char* word) {
    TrieNode* node = root;
    for (int i = 0; word[i] != '\0'; i++) {
        int index = word[i] - 'a';
        if (node->children[index] == NULL) {
            node->children[index] = malloc(sizeof(TrieNode));
        }
        node = node->children[index];
    }
    node->isEndOfWord = true;
}
What is the main bug in this code?
medium
A. New nodes are not initialized, leading to garbage values
B. The loop condition is incorrect and may cause infinite loop
C. The isEndOfWord flag is set too early
D. The root pointer is not updated after insertion

Solution

  1. Step 1: Analyze node allocation

    New nodes are allocated with malloc but not initialized, so children pointers and isEndOfWord have garbage values.
  2. Step 2: Consequences of uninitialized nodes

    Uninitialized children can cause incorrect behavior or crashes during further insert/search operations.
  3. Final Answer:

    New nodes are not initialized, leading to garbage values -> Option A
  4. Quick Check:

    Missing initialization = bug [OK]
Hint: Always initialize new Trie nodes after malloc [OK]
Common Mistakes:
  • Ignoring initialization of new nodes
  • Assuming malloc zeros memory
  • Confusing loop condition correctness
5. You want to insert multiple words into a Trie and then count how many words start with the prefix "pre". Which modification to the Trie insert operation helps achieve this efficiently?
hard
A. Store the entire word at each node instead of characters
B. Add a counter in each node that increments every time a word passes through it during insertion
C. Only mark isEndOfWord without any counters
D. Use a linked list instead of an array for children nodes

Solution

  1. Step 1: Understand prefix counting

    To count words with a prefix, each node can keep a count of how many words pass through it.
  2. Step 2: Modify insert to update counters

    During insertion, increment the counter at each node visited. Then prefix count is the counter at prefix's last node.
  3. Final Answer:

    Add a counter in each node that increments every time a word passes through it during insertion -> Option B
  4. Quick Check:

    Prefix count = node counters [OK]
Hint: Use counters in nodes to track prefix occurrences [OK]
Common Mistakes:
  • Not using counters, making prefix count slow
  • Storing full words at nodes wastes space
  • Using linked list slows access
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard