To solve the problem, I iterated directly over the list.Then I checked if the prefix pref
matched the initial substring of the word
. This was achieved by slicing the string word
up to the length of pref
and comparing it with pref
. If they matched, I incremented a counter, which I returned at the end of the function.
class Solution:
def prefixCount(self, words: List[str], pref: str) -> int:
count = 0
for word in words:
if word[:len(pref)] == pref:
count += 1
return count
- Time: O(n.m) where n is the number of strings in the words list and m is the length of the prefix
pref
. - Space: O(1).
