Counting Words With a Given Prefix - Optimized [C++]
IntuitionThe problem involves checking whether each word in the list starts with a specific prefix. The task can be efficiently tackled by leveraging string com
# Intuition
The problem involves checking whether each word in the list starts with a specific prefix. The task can be efficiently tackled by leveraging string comparison methods.

# Approach
1. Iterate through each word in the `words` array.
2. For each word:
   - Check if its size is greater than or equal to the prefix size.
   - Compare the substring of the word (up to the prefix length) with the prefix.
3. Increment a counter for each match.
4. Return the counter.

This approach ensures we only compare valid substrings and avoids unnecessary computations for words shorter than the prefix.

# Complexity
- **Time complexity**: 
  - Iterating through all words takes \(O(n)\), where \(n\) is the number of words.
  - Comparing the prefix with a substring takes \(O(m)\), where \(m\) is the length of the prefix.
  - Overall complexity: \(O(n \cdot m)\).
  
- **Space complexity**: 
  - The algorithm uses a constant amount of extra space, hence \(O(1)\).

# Code with Comments
```cpp
class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        short res = 0; // Counter to store the number of matches
        for (auto &w : words) {
            // Check if the word is at least as long as the prefix
            if (w.size() >= pref.size() && w.compare(0, pref.size(), pref) == 0) {
                res++; // Increment counter if prefix matches
            }
        }
        return res; // Return the total count of matching words
    }
};
```
['C++']