Trie Search Operation in DSA Python - Time & Space Complexity
We want to understand how long it takes to find a word in a trie.
How does the search time change when the word gets longer?
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 search(self, word: str) -> bool:
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
This code checks if a word exists in the trie by following each letter step-by-step.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each character of the word.
- How many times: Once for every letter in the word (length n).
Each extra letter means one more step to check in the trie.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows directly with the word length.
Time Complexity: O(n)
This means the search time grows linearly with the length of the word.
[X] Wrong: "Searching a word in a trie takes time proportional to the number of words stored."
[OK] Correct: The search depends only on the word length, not how many words are in the trie.
Knowing trie search time helps you explain fast word lookups clearly and confidently.
"What if the trie stored words with a fixed maximum length? How would the time complexity change?"
Practice
search operation in a Trie data structure check for?Solution
Step 1: Understand the purpose of search in Trie
The search operation checks if the exact word is stored in the Trie, not just a prefix.Step 2: Differentiate between search and prefix check
While prefix check looks for any starting sequence, search requires the full word to be present and marked as an end of word.Final Answer:
If a given word exists completely in the Trie -> Option AQuick Check:
Search = full word check [OK]
- Confusing search with prefix check
- Thinking search returns true for partial matches
- Assuming search checks for duplicates
Solution
Step 1: Recall Python dictionary membership syntax
Trie children are usually stored in a dictionary. To check if a key exists, usekey in dict.Step 2: Evaluate each option
if char in current_node.children: uses correct Python syntax. Options A, B, and C use invalid or non-existent methods in Python dictionaries.Final Answer:
if char in current_node.children: -> Option AQuick Check:
Use 'in' keyword for dict keys [OK]
- Using non-existent dictionary methods
- Confusing syntax with other languages
- Trying to call methods on dict keys
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
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
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
trie = Trie()
trie.insert('cat')
print(trie.search('cat'))
print(trie.search('ca'))
print(trie.search('bat'))Solution
Step 1: Insert 'cat' into the Trie
The word 'cat' is inserted, marking the last node's is_end as True.Step 2: Search for 'cat', 'ca', and 'bat'
'cat' exists fully with is_end True, so returns True. 'ca' is prefix but not a full word, so returns False. 'bat' is not inserted, so returns False.Final Answer:
True False False -> Option DQuick Check:
Full word present = True, prefix only = False [OK]
- Assuming prefix search returns True
- Not setting is_end flag on insert
- Confusing missing words with prefixes
def search(self, word):
node = self.root
for char in word:
if char in node.children:
node = node.children[char]
else:
return False
return TrueSolution
Step 1: Analyze the return statement
The method returns True after traversing all characters, but it should confirm the word ends here by checking is_end flag.Step 2: Correct the return value
Returnnode.is_endto ensure the word is complete in the Trie, not just a prefix.Final Answer:
Return node.is_end instead of True at the end -> Option BQuick Check:
Check is_end flag to confirm full word [OK]
- Returning True without checking is_end
- Incorrect if condition reversing
- Unnecessary break statements
True if the word exists or if any word in the Trie starts with the given prefix. Which modification to the standard search method achieves this?Solution
Step 1: Understand the difference between full word and prefix search
Full word search requires is_end True; prefix search only requires traversal success.Step 2: Modify return to support prefix search
Return True after successfully traversing all characters without checking is_end to allow prefix matches.Final Answer:
Return True after traversing all characters without checking is_end -> Option CQuick Check:
Prefix search = True if traversal succeeds [OK]
- Checking is_end for prefix search
- Returning False prematurely
- Confusing prefix length with word length
Ready to prove it?
Pass the test and this pattern moves unknown
