Skip to content

Commit ab30e24

Browse files
Add prefix matching support and update test cases
1 parent adb3bbf commit ab30e24

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

trie/test_trie.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -158,9 +158,23 @@ def test_prefix_matching(self):
158158
words = ["prefix", "preface", "prepare", "prevent"]
159159
for word in words:
160160
self.trie.insert(word)
161-
self.assertTrue(all(self.trie.search(word[:i]) for word in words for i in range(3, len(word) + 1)))
161+
162+
# Test exact word matches
163+
for word in words:
164+
self.assertTrue(self.trie.search(word))
165+
166+
# Test prefix matches
167+
for word in words:
168+
for i in range(3, len(word)):
169+
self.assertTrue(self.trie.search(word[:i], is_prefix=True))
170+
171+
# Test that "pre" is found as a prefix but not as a complete word
172+
self.assertTrue(self.trie.search("pre", is_prefix=True))
162173
self.assertFalse(self.trie.search("pre"))
163174

175+
# Test non-existent prefix
176+
self.assertFalse(self.trie.search("pra", is_prefix=True))
177+
164178
def test_edge_cases(self):
165179
self.trie.insert("a")
166180
self.assertTrue(self.trie.search("a"))

trie/trie.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -19,18 +19,18 @@ def insert(self, word):
1919
node = node.children[char]
2020
node.is_end_of_word = True
2121

22-
def search(self, word):
22+
def search(self, word, is_prefix=False):
2323
"""
24-
Search for a word in the trie.
25-
Returns True if the word is found, False otherwise.
24+
Search for a word or prefix in the trie.
25+
Returns True if the word/prefix is found, False otherwise.
2626
Time complexity: O(m), where m is the length of the word.
2727
"""
2828
node = self.root
2929
for char in word:
3030
if char not in node.children:
3131
return False
3232
node = node.children[char]
33-
return node.is_end_of_word
33+
return is_prefix or node.is_end_of_word
3434

3535
def delete(self, word):
3636
"""

0 commit comments

Comments
 (0)