class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TrieNode() # create node if missing
node = node.children[char] # move to child node
node.is_end = True # mark end of word
def starts_with(self, prefix: str) -> list:
node = self.root
for char in prefix:
if char not in node.children:
return [] # prefix not found
node = node.children[char] # move to next node
result = []
self._dfs(node, prefix, result) # collect all words below prefix
return result
def _dfs(self, node, path, result):
if node.is_end:
result.append(path) # found a word
for char, child in node.children.items():
self._dfs(child, path + char, result) # explore children
def prefix_match_hashmap(words, prefix):
return [word for word in words if word.startswith(prefix)]
# Driver code
words = ["all", "alice", "bob"]
prefix = "al"
# Using Trie
trie = Trie()
for w in words:
trie.insert(w)
trie_result = trie.starts_with(prefix)
# Using Hash Map (dictionary keys)
hash_map = {w: True for w in words}
hash_result = prefix_match_hashmap(list(hash_map.keys()), prefix)
print("Trie words with prefix '" + prefix + "':", ", ".join(trie_result))
print("Hash Map words with prefix '" + prefix + "':", ", ".join(hash_result))if char not in node.children:
node.children[char] = TrieNode() # create node if missing
create new trie node for missing character to build prefix path
node = node.children[char] # move to child node
advance current node to next character node
node.is_end = True # mark end of word
mark node as end of a valid word
if char not in node.children:
return [] # prefix not found
stop search if prefix character missing
self._dfs(node, prefix, result) # collect all words below prefix
collect all words starting with prefix by depth-first search
return [word for word in words if word.startswith(prefix)]
filter all words in hash map keys by prefix match
Trie words with prefix 'al': all, alice
Hash Map words with prefix 'al': all, alice