[Easy] 2185. 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.
Examples
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 <= 1001 <= words[i].length, pref.length <= 100words[i]andprefconsist of lowercase English letters.
Thinking Process
- Simple Prefix Matching: Use substring comparison for clarity
- Strings often need frequency maps or two-pointer scans.
- Watch index bounds and empty-string edge cases.
- Stack helps with nested or repeated patterns.
Common Approaches
Typical techniques for this pattern:
| Approach | Time | Space | Notes |
|---|---|---|---|
| Two pointers on string (this problem) | O(n) | O(1) | Palindrome, parsing |
| Hash map / frequency | O(n) | O(k) | Anagram, character counts |
| KMP / rolling hash | O(n) | O(n) | Pattern matching |
| Stack parsing | O(n) | O(n) | Decode string, parentheses |
Solution
class Solution {
public:
int prefixCount(vector<string>& words, string pref) {
int cnt = 0;
const int prel = pref.length();
for(auto& word: words) {
if(word.substr(0, prel) == pref) {
cnt++;
}
}
return cnt;
}
};
Solution Explanation
Approach: Two pointers on string (this problem)
Key idea: 1. Simple Prefix Matching: Use substring comparison for clarity
How the code works:
- Simple Prefix Matching: Use substring comparison for clarity
- Strings often need frequency maps or two-pointer scans.
- Watch index bounds and empty-string edge cases.
- Stack helps with nested or repeated patterns.
Walkthrough — input words = ["pay","attention","practice","attend"], pref = "at", expected output 2:
The 2 strings that contain “at” as a prefix are: “attention” and “attend”.
Common Mistakes
- Word shorter than prefix:
substr(0, prel)returns a shorter string, comparison fails correctly - Empty prefix: If
pref = "", all words match (but constraints guaranteepref.length >= 1) - Prefix equals word: Word still counts (e.g.,
pref = "at",word = "at"→ match) - No matches: Returns 0 correctly
- All words match: Returns
words.length -
Single character prefix: Works correctly with
pref = "a" - Out-of-bounds access: Not checking word length before accessing characters
- Off-by-one errors: Incorrect substring indices
- Case sensitivity: Problem states lowercase only, but worth noting
- Forgetting to increment counter: Missing the increment statement
- Using wrong comparison: Comparing entire word instead of prefix
When to Use This Pattern
- Prefix Matching: Checking if strings start with specific patterns
- Filtering: Selecting items from a collection based on prefix
- Autocomplete: Finding words that start with user input
- String Processing: Text analysis and pattern matching
- Data Validation: Checking format or structure of strings
Related Problems
- LC 208: Implement Trie (Prefix Tree) - More efficient for multiple prefix queries
- LC 211: Design Add and Search Words Data Structure - Trie with wildcard support
- LC 648: Replace Words - Prefix matching with replacement
- LC 14: Longest Common Prefix - Finding common prefix
- LC 720: Longest Word in Dictionary - Prefix-based word selection
Key Takeaways
- Simple Prefix Matching: Use substring comparison for clarity
- Length Safety:
substr(0, prel)automatically handles cases where word is shorter than prefix (returns shorter substring) - Efficient: Linear time complexity, suitable for given constraints
- Readable: Clear and straightforward implementation
References
- LC 2185: Counting Words With a Given Prefix on LeetCode
- LeetCode Discuss — LC 2185: Counting Words With a Given Prefix
- LeetCode Editorial (may require premium)