Trie Insert Operation in DSA C - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The time grows linearly as the word length increases.
Time Complexity: O(n)
This means the time to insert grows directly with the length of the word.
[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.
Knowing how trie insertion scales helps you explain efficient word storage and search, a common topic in coding interviews.
"What if the trie stored only lowercase letters and uppercase letters? How would that affect the time complexity?"
Practice
insert operation in a Trie data structure?Solution
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.Step 2: Differentiate from other operations
Deleting removes words, searching checks presence, counting totals words. Insert specifically adds words.Final Answer:
To add a word character by character into the Trie -> Option AQuick Check:
Insert = Add word [OK]
- Confusing insert with search or delete
- Thinking insert counts words
- Assuming insert removes words
Solution
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.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.Final Answer:
typedef struct TrieNode { struct TrieNode* children[26]; bool isEndOfWord; } TrieNode; -> Option CQuick Check:
Trie node = children array + end flag [OK]
- Using linked list node structure instead of array
- Confusing Trie with binary tree node
- Missing end-of-word boolean
TrieNode* root = createNode();
insert(root, "cat");
bool flag = root->children['c' - 'a']->children['a' - 'a']->children['t' - 'a']->isEndOfWord;
printf("%d", flag);Solution
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).Step 2: Check isEndOfWord flag
Accessing the node for 't' and printing isEndOfWord prints 1 because the word ends there.Final Answer:
1 -> Option DQuick Check:
Inserted word end flag = 1 [OK]
- Assuming isEndOfWord is 0 after insert
- Indexing children incorrectly
- Forgetting to set isEndOfWord during insert
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?Solution
Step 1: Analyze node allocation
New nodes are allocated with malloc but not initialized, so children pointers and isEndOfWord have garbage values.Step 2: Consequences of uninitialized nodes
Uninitialized children can cause incorrect behavior or crashes during further insert/search operations.Final Answer:
New nodes are not initialized, leading to garbage values -> Option AQuick Check:
Missing initialization = bug [OK]
- Ignoring initialization of new nodes
- Assuming malloc zeros memory
- Confusing loop condition correctness
Solution
Step 1: Understand prefix counting
To count words with a prefix, each node can keep a count of how many words pass through it.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.Final Answer:
Add a counter in each node that increments every time a word passes through it during insertion -> Option BQuick Check:
Prefix count = node counters [OK]
- Not using counters, making prefix count slow
- Storing full words at nodes wastes space
- Using linked list slows access
Ready to prove it?
Pass the test and this pattern moves unknown
