2185. Counting Words With a Given Prefix LeetCode Solution

In this guide, you will get 2185. Counting Words With a Given Prefix LeetCode Solution with the best time and space complexity. The solution to Counting Words With a Given Prefix 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. Counting Words With a Given Prefix solution in C++
  4. Counting Words With a Given Prefix solution in Java
  5. Counting Words With a Given Prefix solution in Python
  6. Additional Resources
2185. Counting Words With a Given Prefix LeetCode Solution image

Problem Statement of Counting Words With a Given Prefix

You are given an array of strings words and a string pref.
Return the number of strings in words that contain pref as a prefix.
A prefix of a string s is any leading contiguous substring of s.

Example 1:

Input: words = [“pay”,”attention”,”practice”,”attend”], pref = “at”
Output: 2
Explanation: The 2 strings that contain “at” as a prefix are: “attention” and “attend”.

Example 2:

Input: words = [“leetcode”,”win”,”loops”,”success”], pref = “code”
Output: 0
Explanation: There are no strings that contain “code” as a prefix.

Constraints:

1 <= words.length <= 100
1 <= words[i].length, pref.length <= 100
words[i] and pref consist of lowercase English letters.

Complexity Analysis

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

2185. Counting Words With a Given Prefix LeetCode Solution in C++

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

2185. Counting Words With a Given Prefix LeetCode Solution in Java

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

2185. Counting Words With a Given Prefix LeetCode Solution in Python

class Solution:
  def prefixCount(self, words: list[str], pref: str) -> int:
    return sum(word.startswith(pref) for word in words)
# code by PROGIEZ

Additional Resources

See also  53. Maximum Subarray LeetCode Solution

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