1. Understand the Goal: The user wants a Python implementation of a basic Trie (Prefix Tree) data structure. It needs to support two specific operations: insert (adding a word) and search (checking if a word exists).
-
Analyze the Data Structure (Trie):
- What is a Trie? It's a tree-like structure used for efficient retrieval of keys (usually strings).
- Nodes: Each node represents a character.
- Edges: Edges represent the transition from one character to the next.
- Children: Each node typically has a map (dictionary) of children, where keys are characters and values are child nodes.
- End of Word Marker: A boolean flag (often called
is_end or end_of_word) is needed to distinguish between prefixes and complete words. For example, if "apple" is inserted, "app" is a prefix, but "apple" is a word. If "app" is also inserted, its node needs the flag set to True.
-
Design the Classes:
-
Refining the Implementation (Python specifics):
- Use standard Python classes.
- Type hinting is good practice.
- Comments and docstrings improve readability.
-
Bonus/Refinement (Optional but helpful):
- A
startsWith method is usually standard in Trie problems (like LeetCode 208). While the user didn't explicitly ask for it, adding it makes the answer more complete. However, the prompt specifically asked for insert and search. I will stick to the requested methods to keep it "basic" but maybe mention startsWith as a note or extension if I feel it adds value without cluttering. Decision: Keep it strictly to insert and search as requested to focus on the core logic, but ensure the code is clean.
-
Writing the Code (Mental Draft):
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
-
Adding Usage Examples:
- Create a Trie instance.
- Insert words ("apple", "app").
- Search for existent ("apple").
- Search for non-existent ("bat").
- Search for prefix but not word ("ap") -> Should return False.
- Search for word after insertion ("app") -> Should return True.
-
Formatting the Output:
- Explanation of how it works.
- The Code block.
- Example usage block.
- Time/Space complexity analysis (good interview prep style).
-
Final Review of the Request:
- "Implement a basic Trie" -> Check.
- "Python" -> Check.
- "Methods for insert and search" -> Check.
-
Constructing the Final Response: (This aligns with the provided good response).
- Define
TrieNode.
- Define
Trie.
- Implement
insert.
- Implement
search.
- Provide example usage.
- Briefly explain complexity.
This thought process moves from understanding requirements to architectural design, coding, verification, and finally structuring the explanation for the user.
Here is a clean, Pythonic implementation of a Trie (Prefix Tree).
A Trie consists of Nodes. Each node contains a dictionary of children nodes and a boolean flag to mark the end of a word.
Python Implementation
class TrieNode:
def __init__(self):
# Dictionary mapping character to the next TrieNode
self.children = {}
# Marks the end of a valid word
self.is_end_of_word = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
"""
Inserts a word into the trie.
Time Complexity: O(m) where m is the length of the word.
"""
node = self.root
for char in word:
# If the character is not already in the children, add it
if char not in node.children:
node.children[char] = TrieNode()
# Move to the next node
node = node.children[char]
# Mark the end of the word
node.is_end_of_word = True
def search(self, word: str) -> bool:
"""
Returns True if the word is in the trie, False otherwise.
Time Complexity: O(m)
"""
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
# Must check if this node marks the end of a word
return node.is_end_of_word
def starts_with(self, prefix: str) -> bool:
"""
(Bonus Method) Returns True if there is any word in the trie
that starts with the given prefix.
"""
node = self.root
for char in prefix:
if char not in node.children:
return False
node = node.children[char]
return True
Example Usage
Here is how you would use the class:
# Initialize the Trie
trie = Trie()
# Insert words
trie.insert("apple")
trie.insert("app")
trie.insert("bat")
# Search for words
print(trie.search("app")) # Output: True
print(trie.search("apple")) # Output: True
print(trie.search("appl")) # Output: False (prefix exists, but not a word)
# Check prefixes
print(trie.starts_with("appl")) # Output: True
print(trie.starts_with("bat")) # Output: True
print(trie.starts_with("cat")) # Output: False
How it works:
- Structure: The
root starts empty.
- Insert ("app"):
- The root creates a child node for
'a'.
- The
'a' node creates a child node for 'p'.
- The first
'p' node creates a child node for the second 'p'.
- The second
'p' node has is_end_of_word set to True.
- Search ("ap"):
- The traverser finds
'a', then finds 'p'.
- However, the node at
'p' has is_end_of_word = False (because we only inserted "app" and "apple"), so it returns False.