We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Count Prefixes of a Given String

Difficulty: Easy


Problem Description

You are given a string array words and a string s, where words[i] and s comprise only of lowercase English letters. Return the number of strings in words that are a prefix of s. A prefix of a string is a substring that occurs at the beginning of the string.


Key Insights

  • A prefix is defined as a substring that must start at the beginning of the string s.
  • Each word in words needs to be checked to see if it matches the start of s.
  • Words can be repeated, and each occurrence should be counted.

Space and Time Complexity

Time Complexity: O(n * m) where n is the length of words and m is the maximum length of a string in words. Space Complexity: O(1) since we are using a constant amount of space for counting.


Solution

To solve the problem, we will iterate through each word in the words array and check if it is a prefix of the string s. We can use the string method startswith() to perform this check efficiently. We maintain a counter to track the number of prefixes found.


Code Solutions

def countPrefixes(words, s):
    count = 0
    for word in words:
        if s.startswith(word):
            count += 1
    return count
← Back to All Questions