File tree 2 files changed +19
-5
lines changed
2 files changed +19
-5
lines changed Original file line number Diff line number Diff line change @@ -158,9 +158,23 @@ def test_prefix_matching(self):
158
158
words = ["prefix" , "preface" , "prepare" , "prevent" ]
159
159
for word in words :
160
160
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 ))
162
173
self .assertFalse (self .trie .search ("pre" ))
163
174
175
+ # Test non-existent prefix
176
+ self .assertFalse (self .trie .search ("pra" , is_prefix = True ))
177
+
164
178
def test_edge_cases (self ):
165
179
self .trie .insert ("a" )
166
180
self .assertTrue (self .trie .search ("a" ))
Original file line number Diff line number Diff line change @@ -19,18 +19,18 @@ def insert(self, word):
19
19
node = node .children [char ]
20
20
node .is_end_of_word = True
21
21
22
- def search (self , word ):
22
+ def search (self , word , is_prefix = False ):
23
23
"""
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.
26
26
Time complexity: O(m), where m is the length of the word.
27
27
"""
28
28
node = self .root
29
29
for char in word :
30
30
if char not in node .children :
31
31
return False
32
32
node = node .children [char ]
33
- return node .is_end_of_word
33
+ return is_prefix or node .is_end_of_word
34
34
35
35
def delete (self , word ):
36
36
"""
You can’t perform that action at this time.
0 commit comments