We are going to implement a Trie (prefix tree) with two methods: insert and search.
Each node in the Trie will be a dictionary (or we can have a Node class, but for simplicity we use a dictionary).
We'll have a root node which is an empty dictionary.
For insert, we traverse each character in the word, creating nodes as necessary, and mark the end of a word with a special key (like 'end').
For search, we traverse the Trie and check if we can find the word and that it ends at a node marked as the end of a word.
However, note that the problem says "basic Trie", so we don't need to implement startsWith (prefix search) unless specified.
But the typical Trie also has startsWith. Since the problem only asks for insert and search, we'll do exactly that.
Let's design:
We can have a class Trie with:
- init: initializes the root as a dictionary.
- insert(word): inserts a word into the Trie.
- search(word): returns True if the word is in the Trie, else False.
However, note: the problem says "Implement a basic Trie", so we are going to use a dictionary for each node.
But note: the node structure can be:
node = {
'children': {} # mapping from character to next node
'is_end': False
}
Alternatively, we can use a nested dictionary without a separate 'children' key, but then we have to store the 'is_end' flag somewhere.
Let me do:
root = {} # the root node is a dictionary that maps characters to other dictionaries (nodes)
But then how to mark the end? We can have a special key in the dictionary, like 'end' set to True.
Example:
insert("apple")
root = {
'a': {
'p': {
'p': {
'l': {
'e': {
'end': True
}
}
}
}
}
}
But then when we search, we have to check for the existence of the 'end' key at the last node.
Alternatively, we can have a separate class for node, but the problem says basic, so let's use a dictionary and a special key.
However, note that the special key might conflict with a character? We can choose a key that is not a letter, like 'is_end'.
But what if we want to store the word? We don't need to, we just need to know if it's the end.
Let's do:
We'll use a dictionary for each node, and we'll store the children under the keys of the characters.
We'll use a key called 'end' to mark the end of a word.
Steps for insert:
node = root
for char in word:
if char not in node:
node[char] = {} # create a new node (empty dictionary)
node = node[char] # move to the next node
node['end'] = True # mark the end
Steps for search:
node = root
for char in word:
if char not in node:
return False
node = node[char]
return 'end' in node # check if this node marks the end of a word
However, note: what if we insert "apple" and then search for "app"? We don't want to return True because "app" is not inserted.
So we must check the 'end' flag.
But what if we insert "app" and then "apple"? Then the node for the second 'p' in "app" will have 'end' set to True, and then we add more children for 'l' and 'e'.
That's okay because when we search for "app", we will see the 'end' in the node for the second 'p'.
So the above works.
However, note: the root node is a dictionary that may have the 'end' key? That would mean the empty string is inserted.
But we are not inserting the empty string. So the root node won't have 'end' unless we insert the empty string.
But what if we want to insert the empty string? The problem doesn't specify. Let's assume we don't need to handle the empty string.
But to be safe, we can adjust: the root node is just a dictionary of children, and we don't put 'end' in the root unless we insert an empty string.
However, the above code for insert would set 'end' in the root if word is empty? Let's see:
if word is empty, then the for loop does nothing, and then we set node['end'] = True, and node is root.
So if we want to support empty string, we can. Otherwise, we can check for empty string and handle it.
Since the problem says "basic", let's not worry about the empty string.
But note: the problem says "Implement a basic Trie", so we are going to assume non-empty strings? Actually, the problem doesn't specify.
Let's read: "Implement a basic Trie in Python with methods for insert and search"
We'll implement for non-empty strings? But the above code would work for empty string too.
However, if we want to avoid empty string, we can check at the beginning of insert and search.
But let's not overcomplicate. We'll implement as above, and if the word is empty, then we set the root's 'end' to True.
But then when we search for empty string, we check if root has 'end'. That's consistent.
However, note that the root node is shared for all words. So if we insert an empty string, then the root node will have 'end' set to True.
But what if we insert "a" and then the empty string? Then the root node will have both the child 'a' and the key 'end'. That's okay.
So we'll go with this.
Let's code accordingly.
But note: the problem doesn't specify if we need to support duplicate inserts. Typically, a Trie doesn't store duplicates, but if we insert the same word twice, we just set the same 'end' to True again. That's okay.
So we are ready.
However, note: the problem says "basic", so we are not going to implement deletion or other operations.
Let's code:
We'll create a class Trie with:
def __init__(self):
self.root = {}
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node:
node[char] = {}
node = node[char]
node['end'] = True
def search(self, word: str) -> bool:
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return 'end' in node
But wait, what if we search for a word that is a prefix of an inserted word? For example, we inserted "apple", and we search for "app". We return False because the node for the second 'p' does not have 'end'? Actually, in our insert for "apple", we set 'end' only at the last node (for 'e'). So when we search for "app", we get to the node for the second 'p' and then check for 'end' which is not there -> False. That's correct.
What if we insert "app" and then "apple"? Then the node for the second 'p' has 'end' set to True (from "app") and also has a child 'l' (from "apple"). Then when we search for "app", we get True. When we search for "apple", we get to the node for 'e' and see 'end' -> True.
So it works.
However, note: the above representation uses a dictionary for each node, and the special key 'end'. But what if we want to use a class for node? The problem says basic, so we can stick to dictionary.
But let me think: what if we want to store more information? Then a class would be better. But the problem only requires insert and search.
We'll go with the dictionary.
However, note: the above code will break if we try to insert a word that has a character that is the same as the special key 'end'. But we are using 'end' as a key that is not a character (since characters are single letters). So unless we have a word that contains the string "end" as a character? No, because each character is a single character. So we are safe.
But what if we want to use a special key that is not a string? We can use a tuple or something. But 'end' is a string of length 3, and our characters are single characters, so no overlap.
Alternatively, we can use a boolean flag in a class. But with dictionary, we are using a string key.
Let's stick to the dictionary with 'end' as a key.
But note: when we traverse, we are only looking for the characters in the word. The 'end' key is only used at the last node to mark the end.
So we are safe.
Let's test with an example:
t = Trie()
t.insert("apple")
t.search("apple") # True
t.search("app") # False
Then insert "app"
t.insert("app")
t.search("app") # True
Now, what about a word that is a prefix of another? We covered.
What about a word that shares a prefix? e.g., "app" and "apple" share the prefix "app". That works.
What about a word that is a suffix? e.g., "apple" and "banana"? They don't share, so they are in separate branches.
So the above should work.
However, note: the problem says "basic", so we don't need to handle case sensitivity? We'll assume all lowercase.
But what if we get uppercase? We can convert to lowercase in insert and search? The problem doesn't specify.
Since it's a basic Trie, let's assume we are dealing with lowercase letters only.
But to be safe, we can convert the word to lowercase in both insert and search? Or we can leave it to the user.
Since the problem doesn't specify, we'll leave it as is.
Let's code accordingly.
But note: the problem says "Implement a basic Trie", so we are just going to implement the data structure.
We'll write the class as described.
However, note that the root node is a dictionary that may have the 'end' key if we insert the empty string.
But if we don't insert the empty string, then the root node will never have 'end'.
So the code is:
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for char in word:
node = node.setdefault(char, {})
node['end'] = True
def search(self, word):
node = self.root
for char in word:
if char not in node:
return False
node = node[char]
return 'end' in node
We can use setdefault to make the insert a bit shorter.
But note: setdefault returns the value for the key if exists, otherwise sets it to the default (empty dict) and returns that.
So we can do:
node = node.setdefault(char, {})
That's the same as:
if char not in node:
node[char] = {}
node = node[char]
So it's fine.
Let me test with an example:
t = Trie()
t.insert("apple")
print(t.root)
Expected: {'a': {'p': {'p': {'l': {'e': {'end': True}}}}}
t.insert("app")
print(t.root)
Now the node for the second 'p' should have 'end': True and also child 'l'?
Actually, after inserting "app", the node for the second 'p' will have 'end': True and then when we inserted "apple", we added the child 'l' to that same node? Wait, no.
Let's break down:
Insert "apple":
start at root: {}
char 'a': root becomes {'a': {}}
node = root['a'] -> {}
char 'p': node becomes {'p': {}} (so root['a'] becomes {'p': {}})
node = node['p'] -> {}
char 'p': node becomes {'p': {}} (so the first 'p' node becomes {'p': {}})
node = node['p'] -> {}
char 'l': node becomes {'l': {}}
node = node['l'] -> {}
char 'e': node becomes {'e': {}}
node = node['e'] -> {}
then set node['end'] = True -> so the node for 'e' becomes {'end': True}
So after "apple", the structure is:
root = {
'a': {
'p': {
'p': {
'l': {
'e': {
'end': True
}
}
}
}
}
}
Now insert "app":
start at root:
char 'a': exists, node = root['a'] -> the node that has key 'p'
char 'p': exists, node = node['p'] -> the node that has key 'p'
char 'p': exists? The current node (which is the node for the first 'p') has key 'p'? Yes, because from "apple" we have that.
Then node = node['p'] -> the node for the second 'p' (which currently has key 'l').
Then we set node['end'] = True. So now the node for the second 'p' becomes:
{
'l': { ... }, # from before
'end': True
}
So after both inserts, the node for the second 'p' has both 'l' and 'end'.
Now when we search "app", we go to the node for the second 'p' and see 'end' -> True.
And for "apple", we go to the node for 'e' and see 'end' -> True.
So it works.
But note: the node for the second 'p' has two keys: 'l' and 'end'. That's okay because we are using a dictionary.
However, what if we want to store more than one word that ends at the same node? That's not possible because the word is exactly the same? Actually, if we insert the same word twice, we just set 'end' to True again. So it's idempotent.
So we are good.
Let's write the code accordingly.
But note: the problem says "basic", so we are not going to implement more.
However, what about non-alphabet characters? The Trie can be used for any set of characters. Our implementation uses a dictionary, so it can handle any hashable character (like strings of length 1). But if we want to handle multi-character? No, because we are iterating by each character in the word, and each character is a string of length 1.
So we are assuming that the word is a string of single characters.
That's typical for a Trie.
Let's code.
One more thing: we might want to have a method to check if a prefix exists? But the problem doesn't ask for it.
So we'll just do insert and search.
Let's write the class.
Here's a basic Trie implementation in Python with insert and search methods:
class TrieNode:
def __init__(self):
self.children = {} # Maps character to child TrieNode
self.is_end = False # Marks end of a word
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
"""Inserts a word into the trie."""
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: str) -> bool:
"""Returns True if the word is in the trie."""
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
# Example usage:
if __name__ == "__main__":
trie = Trie()
# Insert words
trie.insert("apple")
trie.insert("app")
trie.insert("banana")
# Search for words
print(trie.search("apple")) # True
print(trie.search("app")) # True
print(trie.search("appl")) # False (prefix but not complete word)
print(trie.search("banana")) # True
print(trie.search("ban")) # False
print(trie.search("orange")) # False
Key Points:
-
Structure: Each TrieNode has:
children: Dictionary mapping characters to child nodes.
is_end: Boolean flag indicating if the node represents the end of a valid word.
-
Insert:
- Traverse the trie character by character.
- Create new nodes as needed.
- Mark the final node's
is_end as True.
-
Search:
- Traverse the trie for all characters in the word.
- If any character is missing, return
False.
- After traversal, return the
is_end flag of the final node (ensures complete word match, not just prefix).
Time Complexity:
- Insert: O(L) where L is the length of the word.
- Search: O(L) for the same reason.
Space Complexity:
- O(N × L) in the worst case, where N is the number of words and L is average word length (due to shared prefixes).
This implementation efficiently handles word storage and lookup, making it suitable for autocomplete, spell-checkers, and IP routing tables.