array and hashmap November 5, 2022

Counting words with a given prefix

Time O(n) Space O(1) Open original problem

We will iterate over the words and count the number of words that start with the given prefix.

class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        res = 0
        for word in words:
            res += 1 if word.startswith(pref) else 0
        return res

Time Complexity: O(n)
Space Complexity: O(1)