Skip to content

2185. Counting Words With a Given Prefix 👍

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
class Solution {
 public:
  int prefixCount(vector<string>& words, string pref) {
    return ranges::count_if(
        words, [&](const string& word) { return word.find(pref) == 0; });
  }
};
1
2
3
4
5
class Solution {
  public int prefixCount(String[] words, String pref) {
    return (int) Arrays.stream(words).filter(w -> w.startsWith(pref)).count();
  }
}
1
2
3
class Solution:
  def prefixCount(self, words: list[str], pref: str) -> int:
    return sum(word.startswith(pref) for word in words)