📖 Scenario: Imagine you are building a simple phone contact search system. You want to quickly check if a contact name exists in your phone book. A Trie (prefix tree) is a great way to store and search names efficiently.
🎯 Goal: Build a Trie data structure and implement a search operation to check if a given contact name exists in the Trie.
📋 What You'll Learn
Create a TrieNode class with a dictionary for children and a boolean to mark end of word
Create a Trie class with insert and search methods
Insert given contact names into the Trie
Search for a specific contact name and print if it exists or not
💡 Why This Matters
🌍 Real World
Tries are used in search engines, autocomplete features, and contact lists to quickly find words or names.
💼 Career
Understanding Tries helps in roles involving text processing, search optimization, and building efficient data retrieval systems.
Progress0 / 4 steps
1
Create TrieNode and Trie classes with insert method
Create a class called TrieNode with an attribute children as an empty dictionary and is_end_of_word as False. Then create a class called Trie with an __init__ method that initializes root as a TrieNode. Add an insert method in Trie that takes a string word and inserts it into the Trie.
DSA Python
Hint
Think of TrieNode as a box holding letters and a flag to mark if a word ends there. The insert method walks through each letter and adds nodes if missing.
2
Insert given contact names into the Trie
Create a list called contacts with these exact strings: 'alice', 'bob', 'carol', 'dave'. Then create a Trie object called trie and insert each contact from contacts into trie using the insert method.
DSA Python
Hint
Use a list to hold the contact names exactly as given. Then create the Trie and insert each name one by one.
3
Add search method to Trie to find contact names
Add a method called search in the Trie class that takes a string word and returns True if the word exists in the Trie, otherwise False. Use a variable node starting at self.root and iterate over each character in word. If a character is not in node.children, return False. After the loop, return the value of node.is_end_of_word.
DSA Python
Hint
Walk through the Trie nodes for each letter. If a letter is missing, return False. If all letters found, check if it marks the end of a word.
4
Search for a contact and print the result
Use the search method of trie to check if the contact name 'carol' exists. Print "Found" if it exists, otherwise print "Not Found".
DSA Python
Hint
Use an if-else statement to print "Found" if trie.search('carol') returns True, else print "Not Found".
Practice
(1/5)
1. What does the search operation in a Trie data structure check for?
easy
A. If a given word exists completely in the Trie
B. If a given prefix exists in the Trie
C. If the Trie is empty
D. If the Trie contains duplicate words
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 A
Quick Check:
Search = full word check [OK]
Hint: Search checks full word presence, not just prefix [OK]
Common Mistakes:
Confusing search with prefix check
Thinking search returns true for partial matches
Assuming search checks for duplicates
2. Which of the following is the correct way to check if a character node exists in a Trie during search in Python?
Trie children are usually stored in a dictionary. To check if a key exists, use key 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 A
Quick Check:
Use 'in' keyword for dict keys [OK]
Hint: Use 'in' keyword to check dictionary keys in Python [OK]
Common Mistakes:
Using non-existent dictionary methods
Confusing syntax with other languages
Trying to call methods on dict keys
3. What will be the output 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):
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'))
medium
A. False\nFalse\nFalse
B. True\nTrue\nFalse
C. True\nFalse\nTrue
D. True\nFalse\nFalse
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 D
Quick Check:
Full word present = True, prefix only = False [OK]
Hint: Search returns True only if full word and is_end True [OK]
Common Mistakes:
Assuming prefix search returns True
Not setting is_end flag on insert
Confusing missing words with prefixes
4. Identify the error in the following Trie search method and select the fix:
def search(self, word):
node = self.root
for char in word:
if char in node.children:
node = node.children[char]
else:
return False
return True
medium
A. Change 'if char in node.children' to 'if char not in node.children'
B. Return node.is_end instead of True at the end
C. Initialize node as None before loop
D. Add a break statement inside the loop
Solution
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
Return node.is_end to 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 B
Quick Check:
Check is_end flag to confirm full word [OK]
Hint: Always check is_end flag after traversal [OK]
Common Mistakes:
Returning True without checking is_end
Incorrect if condition reversing
Unnecessary break statements
5. You want to implement a search in a Trie that returns 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?
hard
A. Return node.is_end only after traversal
B. Return False if any character is missing during traversal
C. Return True after traversing all characters without checking is_end
D. Return True only if the prefix length equals the word length
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 C
Quick Check:
Prefix search = True if traversal succeeds [OK]
Hint: For prefix search, ignore is_end flag, return True if path exists [OK]
Common Mistakes:
Checking is_end for prefix search
Returning False prematurely
Confusing prefix length with word length
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.