Opening the reading…
Opening the reading…
SLIDING WINDOW › FIXED SIZE SLIDING-WINDOW
Open — the attempt gate is not wired up yet
This editorial is meant to unlock after you have run the problem at least once, with the worked solution behind one further deliberate click. That needs per-learner unlock state nothing stores today, so for now the whole article is open.
Try it yourself first →A substring of length k is a window with exactly k positions. If you count its vowels directly, then move the window one position to the right, most of the characters are unchanged: only the old leftmost character leaves and one new character enters. The next vowel count is therefore the old count minus one possible vowel plus one possible vowel.
Start with the first k characters so the count is correct before any sliding begins. Then examine each following character as the new right edge. Remove the character k positions behind it, add the new character, and record the largest count seen. Every length-k substring becomes one of these windows, so the largest recorded count is the answer.
| MEASURE | BOUND | WHY |
|---|---|---|
| Time | O(n) | The first window examines k characters and the sliding loop examines each of the remaining n - k characters once. Each position is classified by the vowel test at most when it enters and when it leaves, so the total work is proportional to n rather than to the number of possible windows times k. |
| Space | O(1) extra | The algorithm stores only the current count, the maximum, and a constant-size vowel predicate; the input string is not copied and the returned integer needs no output storage. The bound stays O(1) even for the worst input shape because the window size does not create an auxiliary structure. |
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
int maxVowels(string s, int k) {
int n = static_cast<int>(s.size());
auto isVowel = [](char c) {
return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
};
int count = 0;
for (int i = 0; i < k; ++i) {
if (isVowel(s[i])) {
++count;
}
}
int maxCount = count;
for (int i = k; i < n; ++i) {
if (isVowel(s[i - k])) {
--count;
}
if (isVowel(s[i])) {
++count;
}
maxCount = max(maxCount, count);
}
return maxCount;
}
};The index i names the character entering the window, so the character leaving is exactly k positions earlier at i - k. After the two conditional updates, the current window is s[i - k + 1] through s[i]. Keeping this relationship explicit is the key to avoiding rescans: the count always describes the same window that maxCount is comparing.