Counting Words With a Given Prefix

The problem is asking us to find the number of strings in a given array that have a specific prefix. We’ll iterate through the array and check the beginning of each string to see if it matches the given prefix. If it does, we’ll increment our counter.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def prefixCount(self, words: List[str], pref: str) -> int:
        # Initialize a counter for the number of words that contain the prefix
        count = 0

        # Iterate through the words in the array
        for word in words:
            # If the word starts with the given prefix, increment the count
            if word.startswith(pref):
                count += 1

        # Return the final count
        return count

Explanation

  • We utilize the built-in startswith method, which checks if the given string starts with a specific prefix.
  • If the current word starts with the given prefix, we increment the count.
  • We return the final count.

Example

For the input words = ["pay","attention","practice","attend"] and pref = "at", the method would return 2 since the words “attention” and “attend” start with “at”.