📖 Scenario: You are building a simple search feature for a phone contacts app. When a user types some letters, the app should quickly find all contact names that start with those letters.To do this efficiently, you will use a Trie data structure. A Trie stores words so you can find all words with a given prefix fast.
🎯 Goal: Build a Trie to store contact names, then search for all contacts starting with a given prefix.
📋 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 prefix search methods
Insert given contact names into the Trie
Search and return all contact names starting with a given prefix
💡 Why This Matters
🌍 Real World
Tries are used in search engines, autocomplete features, and spell checkers to quickly find words starting with certain letters.
💼 Career
Understanding Tries helps in roles involving search optimization, text processing, 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. Finally, add an insert method to 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 if a word ends there. The Trie has a root node and an insert method to add words letter by letter.
2
Insert given contacts into the Trie
Create a list called contacts with these exact strings: 'alice', 'bob', 'alicia', 'bobby', 'alex'. Then create a Trie object called trie and insert each contact from contacts into trie using the insert method.
DSA Python
Hint
Make a list with the exact contact names. Then create a Trie object and insert each contact using a for loop.
3
Add prefix search method to find all contacts starting with prefix
Add a method called starts_with to the Trie class that takes a string prefix and returns a list of all words in the Trie that start with prefix. Use a helper function inside starts_with to recursively collect all words from the node where the prefix ends.
DSA Python
Hint
First find the node where the prefix ends. Then use a small recursive function to find all words below that node by exploring children.
4
Print all contacts starting with given prefix
Use the starts_with method of trie to find all contacts starting with the prefix 'ali'. Then print the resulting list.
DSA Python
Hint
Call trie.starts_with('ali') and print the list it returns.
Practice
(1/5)
1. What is the main purpose of using a Trie data structure in prefix search?
easy
A. To perform arithmetic operations quickly
B. To sort words alphabetically
C. To store numbers in sorted order
D. To efficiently find all words starting with a given prefix
Solution
Step 1: Understand Trie usage
A Trie stores characters of words in a tree structure, allowing quick prefix lookups.
Step 2: Identify prefix search goal
Prefix search means finding all words that start with a given prefix efficiently.
Final Answer:
To efficiently find all words starting with a given prefix -> Option D
Quick Check:
Trie = prefix search efficiency [OK]
Hint: Trie nodes represent prefixes for fast search [OK]
Common Mistakes:
Confusing Trie with sorting data structure
Thinking Trie is for arithmetic
Assuming Trie stores whole words only
2. Which of the following is the correct way to insert a word into a Trie node in Python?
easy
A. node.children.add(char)
B. node.children[char] = TrieNode() if char not in node.children else node.children[char]
C. node.children.append(char)
D. node.children[char] = char
Solution
Step 1: Understand Trie children structure
Trie children are usually stored in a dictionary mapping characters to TrieNode objects.
Step 2: Correct insertion syntax
We check if character exists; if not, create new TrieNode and assign it to children dictionary.
Final Answer:
node.children[char] = TrieNode() if char not in node.children else node.children[char] -> Option B
Quick Check:
Insert word by mapping char to TrieNode [OK]
Hint: Use dictionary keys for children, not list methods [OK]
Common Mistakes:
Using list methods like append or add on dictionary
Assigning character instead of TrieNode
Not checking if child node exists before insertion
3. Given the following code snippet, what will be the output of trie.starts_with('app')?
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 starts_with(self, prefix):
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
trie = Trie()
trie.insert('apple')
trie.insert('app')
print(trie.starts_with('app'))
medium
A. Error
B. False
C. True
D. None
Solution
Step 1: Insert words 'apple' and 'app'
Both words share prefix 'app', so nodes for 'a', 'p', 'p' exist in Trie.
Step 2: Check starts_with('app')
Function checks each character in 'app' exists in children; all found, so returns True.
Final Answer:
True -> Option C
Quick Check:
Prefix 'app' exists in Trie = True [OK]
Hint: If prefix nodes exist, starts_with returns True [OK]
Common Mistakes:
Confusing starts_with with full word search
Expecting False because 'app' is prefix, not full word
Ignoring that 'app' was inserted
4. Identify the bug in the following Trie starts_with method and select the correct fix:
def starts_with(self, prefix):
node = self.root
for char in prefix:
if char in node.children:
node = node.children[char]
else:
return True
return False
medium
A. Return False inside else, return True after loop
B. Return True inside else, return True after loop
C. Return False inside else, return False after loop
D. Return True inside else, return False after loop
Solution
Step 1: Analyze current else return
Currently, if char not found, method returns True incorrectly; should return False.
Step 2: Correct return values
Return False inside else (prefix not found), and True after loop (prefix fully matched).
Final Answer:
Return False inside else, return True after loop -> Option A
Quick Check:
Prefix missing = False, prefix found = True [OK]
Hint: Return False if char missing, True if all found [OK]
Common Mistakes:
Returning True when prefix char missing
Returning False after loop instead of True
Confusing else and after loop returns
5. You want to find all words in a Trie that start with the prefix "car". Which approach correctly extends the prefix search to list all such words?
hard
A. Traverse to node of 'car' prefix, then recursively collect all words from that node
B. Search each word in Trie and check if it starts with 'car' using string slicing
C. Insert 'car' as a word and then search for it
D. Use a hash map to store all words and filter by prefix
Solution
Step 1: Locate prefix node in Trie
Traverse Trie nodes for 'c', 'a', 'r' to reach prefix node.
Step 2: Recursively collect words from prefix node
From prefix node, explore all child nodes to build and collect complete words starting with 'car'.
Final Answer:
Traverse to node of 'car' prefix, then recursively collect all words from that node -> Option A
Quick Check:
Prefix node + recursion = all words with prefix [OK]
Hint: Find prefix node, then DFS to collect words [OK]
Common Mistakes:
Checking all words instead of using Trie structure
Inserting prefix as word incorrectly
Using unrelated data structures like hash map
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.