{x}
blog image

Count Prefixes of a Given String

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. A substring is a contiguous sequence of characters within a string.

 

Example 1:

Input: words = ["a","b","c","ab","bc","abc"], s = "abc"
Output: 3
Explanation:
The strings in words which are a prefix of s = "abc" are:
"a", "ab", and "abc".
Thus the number of strings in words which are a prefix of s is 3.

Example 2:

Input: words = ["a","a"], s = "aa"
Output: 2
Explanation:
Both of the strings are a prefix of s. 
Note that the same string can occur multiple times in words, and it should be counted each time.

 

Constraints:

  • 1 <= words.length <= 1000
  • 1 <= words[i].length, s.length <= 10
  • words[i] and s consist of lowercase English letters only.

Solution Explanation: Counting Prefixes

The problem asks to count how many strings in the input array words are prefixes of the given string s. A prefix is a substring that appears at the beginning of a string.

Approach

The most straightforward approach is to iterate through each string in the words array and check if it's a prefix of s. We can efficiently do this using the startsWith() method (or its equivalent in different programming languages) which directly checks if one string is a prefix of another. We increment a counter for each string that satisfies this condition.

Time and Space Complexity

  • Time Complexity: O(m*n), where 'm' is the length of words array and 'n' is the maximum length of a string in words and length of string s. In the worst case, we might need to compare up to the length of the shortest string in each iteration of the outer loop.
  • Space Complexity: O(1). We only use a constant amount of extra space to store the counter.

Code Implementation in Different Languages

Python

class Solution:
    def countPrefixes(self, words: List[str], s: str) -> int:
        count = 0
        for word in words:
            if s.startswith(word):
                count += 1
        return count
 

Java

class Solution {
    public int countPrefixes(String[] words, String s) {
        int count = 0;
        for (String word : words) {
            if (s.startsWith(word)) {
                count++;
            }
        }
        return count;
    }
}

C++

class Solution {
public:
    int countPrefixes(vector<string>& words, string s) {
        int count = 0;
        for (const string& word : words) {
            if (s.rfind(word, 0) == 0) { //Efficient prefix check in C++
                count++;
            }
        }
        return count;
    }
};

JavaScript

/**
 * @param {string[]} words
 * @param {string} s
 * @return {number}
 */
var countPrefixes = function(words, s) {
    let count = 0;
    for (let word of words) {
        if (s.startsWith(word)) {
            count++;
        }
    }
    return count;
};

Go

func countPrefixes(words []string, s string) int {
    count := 0
    for _, word := range words {
        if strings.HasPrefix(s, word) {
            count++
        }
    }
    return count
}

All the above code snippets follow the same basic logic: iterate through words, check if each word is a prefix of s using the appropriate string function, and increment a counter accordingly. The choice of language only affects the syntax and the specific string function used for the prefix check.