2255. Count Prefixes of a Given String LeetCode Solution

In this guide, you will get 2255. Count Prefixes of a Given String LeetCode Solution with the best time and space complexity. The solution to Count Prefixes of a Given String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Count Prefixes of a Given String solution in C++
  4. Count Prefixes of a Given String solution in Java
  5. Count Prefixes of a Given String solution in Python
  6. Additional Resources
2255. Count Prefixes of a Given String LeetCode Solution image

Problem Statement of 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.

See also  2458. Height of Binary Tree After Subtree Removal Queries LeetCode Solution

Complexity Analysis

  • Time Complexity: O(n|\texttt{s}|)
  • Space Complexity: O(1)

2255. Count Prefixes of a Given String LeetCode Solution in C++

class Solution {
 public:
  int countPrefixes(vector<string>& words, string s) {
    return ranges::count_if(
        words, [&](const string& word) { return s.find(word) == 0; });
  }
};
/* code provided by PROGIEZ */

2255. Count Prefixes of a Given String LeetCode Solution in Java

class Solution {
  public int countPrefixes(String[] words, String s) {
    return (int) Arrays.stream(words).filter(word -> s.startsWith(word)).count();
  }
}
// code provided by PROGIEZ

2255. Count Prefixes of a Given String LeetCode Solution in Python

class Solution:
  def countPrefixes(self, words: list[str], s: str) -> int:
    return sum(map(s.startswith, words))
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.