The challenge
Return the largest number of vowels in any substring of exactly k characters. Vowels are a, e, i, o, and u.
Lowercase English letters; 1 ≤ k ≤ n.
Example
abciiidef, k = 3 → 3, from iii.
Use the walkthrough below to inspect the input and each state change.
See Maximum vowels, step by step
Expand, shrink, and inspect the window state.
9 elements · zero-based indicesk = 3
Current windowRecorded answerOutside window
- Left
- 0
- Right
- -1
- Length
- 0
Step 01 / 18
Start with an empty window
Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.
left = 0; right = −1Answer so far
0
View exact input
Input: ["a","b","c","i","i","i","d","e","f"] · k = 3
Current window is empty.
Put it into code
Maintain the count of characters satisfying a predicate. The same template counts any chosen category within a fixed window.
Indices are zero-based. C++ uses C++17 or later.
def max_vowels(s, k):
vowels = set("aeiou")
count = best = 0
for right, char in enumerate(s):
count += char in vowels
if right >= k:
count -= s[right - k] in vowels
if right >= k - 1:
best = max(best, count)
return best#include <algorithm>
#include <array>
#include <deque>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int max_vowels(const string& s, int k) {
auto vowel = [](char c) {
return string("aeiou").find(c) != string::npos;
};
int count = 0, best = 0;
for (int r = 0; r < (int)s.size(); ++r) {
count += vowel(s[r]);
if (r >= k) count -= vowel(s[r - k]);
if (r >= k - 1) best = max(best, count);
}
return best;
}