Bird
Raised Fist0
DSA Cprogramming~5 mins

Trie Insert Operation in DSA C - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Trie Insert Operation
O(n)
Understanding Time Complexity

We want to understand how the time to insert a word into a trie changes as the word gets longer.

How does the number of steps grow when we add longer words?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


// Insert a word into a trie
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] = createNode();
        }
        node = node->children[index];
    }
    node->isEndOfWord = true;
}
    

This code adds each character of the word into the trie, creating new nodes if needed.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop over each character of the input word.
  • How many times: Exactly once per character, so as many times as the word length.
How Execution Grows With Input

Each character in the word causes one step in the loop, so the total steps grow directly with word length.

Input Size (n)Approx. Operations
10About 10 steps
100About 100 steps
1000About 1000 steps

Pattern observation: The time grows linearly as the word length increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to insert grows directly with the length of the word.

Common Mistake

[X] Wrong: "Inserting a word takes constant time because we just add nodes once."

[OK] Correct: Each character must be processed, so longer words take more time, not the same time.

Interview Connect

Knowing how trie insertion scales helps you explain efficient word storage and search, a common topic in coding interviews.

Self-Check

"What if the trie stored only lowercase letters and uppercase letters? How would that affect the time complexity?"

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