Counting Words With a Given Prefix
Problem
Given an array of strings words and a string pref, return the number of strings in words that begin with pref. A string s begins with pref when pref is a prefix of s, meaning the first characters of s match pref exactly.
words = ["pay", "attention", "practice", "attend"], pref = "at"2def prefix_count(words, pref):
count = 0
for w in words:
if w.startswith(pref):
count += 1
return count
function prefixCount(words, pref) {
let count = 0;
for (const w of words) {
if (w.startsWith(pref)) {
count++;
}
}
return count;
}
class Solution {
public int prefixCount(String[] words, String pref) {
int count = 0;
for (String w : words) {
if (w.startsWith(pref)) {
count++;
}
}
return count;
}
}
int prefixCount(vector<string>& words, string pref) {
int count = 0;
for (const string& w : words) {
if (w.rfind(pref, 0) == 0) {
count++;
}
}
return count;
}
Explanation
We just need to count how many words begin with the given prefix pref. There is no clever trick required: walk through the list once and test each word.
For every word w, we ask a single yes/no question: does w start with pref? Most languages give us this directly — startswith in Python, startsWith in JavaScript and Java. In C++ we use w.rfind(pref, 0) == 0, which checks whether pref appears at position 0.
Under the hood, "starts with" compares the characters of pref against the first characters of w. If pref is longer than w, or any character differs, the answer is no. Whenever the answer is yes, we bump a running count.
Example: words = ["pay", "attention", "practice", "attend"], pref = "at". The word "pay" starts with "p", not "a", so it fails. "attention" begins with "at" — count it. "practice" fails. "attend" begins with "at" — count it. The final count is 2.
After checking every word, the value left in count is the answer.