Trie Insert Operation in DSA Python - 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 the word length increases?
Analyze the time complexity of the following code snippet.
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode()
node = node.children[char]
node.is_end = True
This code inserts each character of a word into the trie, creating new nodes if needed.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the word.
- How many times: Once for every character in the word (word length).
Each extra character means one more step to check or add a node.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
Pattern observation: The steps grow directly with the word length.
Time Complexity: O(n)
This means the time to insert grows linearly with the length of the word.
[X] Wrong: "Insertion time depends on the number of words already in the trie."
[OK] Correct: Insertion only depends on the length of the word being inserted, not how many words are stored.
Understanding this helps you explain how tries efficiently handle many words by focusing on word length, not total words.
"What if we changed the insert method to handle only lowercase letters using a fixed-size array instead of a dictionary? How would the time complexity change?"
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 one by one, creating nodes if they don't exist.Step 2: Compare with other operations
Deleting removes words, searching checks presence, counting totals words. Insert specifically adds words.Final Answer:
To add a new word character by character into the Trie -> Option BQuick Check:
Insert = Add word stepwise [OK]
- Confusing insert with search or delete
- Thinking insert counts words
- Assuming insert removes words
"cat" into an empty Trie in Python?Solution
Step 1: Check condition before adding node
We must check if the character node exists before creating a new one to avoid overwriting.Step 2: Move current pointer correctly
After ensuring the node exists, move current to that child node for next character insertion.Final Answer:
for char in "cat": if char not in current.children: current.children[char] = TrieNode(); current = current.children[char] -> Option DQuick Check:
Check existence then add and move [OK]
- Not checking if child node exists before assignment
- Not moving current pointer after insertion
- Overwriting existing nodes
"dog" into a Trie. What will be the printed output after insertion?class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
root = TrieNode()
word = "dog"
current = root
for char in word:
if char not in current.children:
current.children[char] = TrieNode()
current = current.children[char]
current.is_end = True
print(list(root.children.keys()))Solution
Step 1: Insert characters one by one
The first character 'd' is added as a child of root, so root.children has key 'd'.Step 2: Check what is printed
Printing root.children.keys() shows the first level keys, which is ['d'] after insertion.Final Answer:
['d'] -> Option AQuick Check:
Root children keys after insert = ['d'] [OK]
- Expecting all letters at root level
- Printing keys of last node instead of root
- Confusing keys with values
"bat" into a Trie but has a bug. What is the error?class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
root = TrieNode()
word = "bat"
current = root
for char in word:
current.children[char] = TrieNode()
current = current.children[char]
current.is_end = TrueSolution
Step 1: Analyze loop and pointer movement
The line moving current pointer is outside the loop, so current only moves after loop ends, not per character.Step 2: Understand effect on insertion
Nodes for each character are created directly under root (no chaining), and only the last node's is_end is set.Final Answer:
The current pointer is moved outside the loop, causing nodes to not be chained properly -> Option CQuick Check:
Pointer must move inside loop to build chain [OK]
- Moving pointer outside loop
- Not creating nodes conditionally
- Setting is_end too early
["apple", "app", "ape"] into a Trie. After insertion, which of the following statements is TRUE about the Trie structure?Solution
Step 1: Understand shared prefixes in Trie
Words "apple", "app", and "ape" share prefix "ap"; nodes for 'a' and 'p' are shared.Step 2: Check is_end flags for words
"app" ends at second 'p' node, so that node's is_end = True; "apple" continues to 'l' and 'e', so 'l' node is not end, but 'e' node is end.Step 3: Analyze options
The node for 'p' after 'ap' will have is_end = True for both "app" and "ape" is wrong because 'p' node cannot be end for both "app" and "ape"; 'ape' ends at 'e' node. Each word creates a completely separate branch from root is wrong because branches share prefix nodes. The root node's is_end flag will be True after insertion is wrong because root node is not end of any word.Final Answer:
The node for 'l' after "app" exists only for "apple" -> Option AQuick Check:
Shared prefix nodes, is_end marks word ends [OK]
- Assuming each word has separate root branch
- Marking is_end on wrong nodes
- Setting root is_end True incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
