Best Solution for Arrays, Prefix Sum 🚀 in C++, Python and Java || 100% working
Intuition💡 The problem asks to count how many words in the list start with the given prefix. We can use string slicing or substring comparison to check each wor
# Intuition  
💡 The problem asks to count how many words in the list start with the given prefix. We can use string slicing or substring comparison to check each word’s prefix.  

# Approach  
1️⃣ For each word in the list, compare its prefix with the given prefix.  
2️⃣ Slice the word up to the length of the prefix and check if they match.  
3️⃣ If they match, increase the counter.  

# Complexity  
- **Time complexity:** $$O(n \times m)$$, where `n` is the number of words and `m` is the length of the prefix.  
- **Space complexity:** $$O(1)$$, as we only need a few extra variables for the count.  

# Code  

```cpp []
class Solution {
public:
    int prefixCount(vector<string>& words, string pref) {
        int n = pref.size();
        int ans = 0;
        for (string& word : words) {
            if (word.substr(0, n) == pref) {
                ans++;
            }
        }
        return ans;
    }
};
```

```python []
class Solution(object):
    def prefixCount(self, words, pref):
        n = len(pref)
        ans = 0
        for i in words:
            if i[:n] == pref:
                ans += 1
        return ans
```

```java []
class Solution {
    public int prefixCount(String[] words, String pref) {
        int n = pref.length();
        int ans = 0;
        for (String word : words) {
            if (word.startsWith(pref)) {
                ans++;
            }
        }
        return ans;
    }
}
```

🚀 **Counting prefixes across languages!** 😎

<img src="https://assets.leetcode.com/users/images/7b864aef-f8a2-4d0b-a376-37cdcc64e38c_1735298989.3319144.jpeg" alt="upvote" width="150px">

# Connect with me on LinkedIn for more insights! 🌟 Link in bio
['Array', 'String', 'String Matching', 'Python', 'C++', 'Java', 'Python3']