Maximum Number of Vowels in a Substring of Given Length (LeetCode 1456): Solution and Explanation
Return the largest number of vowels found in any substring of s whose length is exactly k.
Intuition
Every candidate substring has the same length k, so the candidates are just the n - k + 1 positions of one window of width k.
Counting the vowels of each window from scratch costs O(k) per window and O(nk) overall, which is too slow for n = 10^5.
Two neighbouring windows share k - 1 characters. When the window moves one step right, one character enters on the right and one leaves on the left, so the vowel count changes by at most one in each direction.
Keep a running count, adjust it with only those two characters, and remember the largest value it reaches.
Approach: Fixed-size sliding window
- Count the vowels in
s[0..k-1]and store it incount. Setbest = count. - For each
ifrom k to n - 1, add one tocountifs[i]is a vowel. - Subtract one from
countifs[i - k], the character leaving the window, is a vowel. - Set
best = max(best, count). - Return
best.
Step-by-step example
s = "abciiidef", k = 3
- First window "abc" (indices 0..2) holds one vowel, 'a'. count = 1, best = 1.
- i = 3: 'i' enters (+1) and 'a' leaves (-1). Window "bci", count = 1.
- i = 4: 'i' enters (+1) and 'b' leaves. Window "cii", count = 2, best = 2.
- i = 5: 'i' enters (+1) and 'c' leaves. Window "iii", count = 3, best = 3.
- i = 6 to 8: "iid", "ide" and "def" hold 2, 2 and 1 vowels, none beats 3. The answer is 3.
Code: Python, Java, C++
1class Solution:
2 def maxVowels(self, s: str, k: int) -> int:
3 vowels = set("aeiou")
4 count = sum(1 for ch in s[:k] if ch in vowels)
5 best = count
6 for i in range(k, len(s)):
7 if s[i] in vowels:
8 count += 1
9 if s[i - k] in vowels:
10 count -= 1
11 best = max(best, count)
12 return best1class Solution {
2 public int maxVowels(String s, int k) {
3 int count = 0;
4 for (int i = 0; i < k; i++) {
5 if (isVowel(s.charAt(i))) count++;
6 }
7 int best = count;
8 for (int i = k; i < s.length(); i++) {
9 if (isVowel(s.charAt(i))) count++;
10 if (isVowel(s.charAt(i - k))) count--;
11 best = Math.max(best, count);
12 }
13 return best;
14 }
15
16 private boolean isVowel(char c) {
17 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
18 }
19}1class Solution {
2public:
3 int maxVowels(string s, int k) {
4 int count = 0;
5 for (int i = 0; i < k; i++) {
6 if (isVowel(s[i])) count++;
7 }
8 int best = count;
9 for (int i = k; i < (int)s.size(); i++) {
10 if (isVowel(s[i])) count++;
11 if (isVowel(s[i - k])) count--;
12 best = max(best, count);
13 }
14 return best;
15 }
16
17private:
18 bool isVowel(char c) {
19 return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u';
20 }
21};Time and space complexity
O(n)
Each character enters the window once and leaves it at most once, and each event is an O(1) membership check.
O(1)
Only the running count, the best count and a fixed five-letter vowel set are stored.
Other approaches
Prefix sums of vowels (time O(n), space O(n))
Build pre[i], the number of vowels in s[0..i-1], then the window starting at j holds pre[j + k] - pre[j] vowels. Take the maximum over all j.
Recount every window (time O(n * k), space O(1))
For every start position count the vowels in the next k characters. Simple, but O(nk) and it times out when both n and k are large.
Common mistakes
- Removing
s[i - k + 1]instead ofs[i - k]. The character that leaves whens[i]enters is exactly k positions behind it. - Forgetting to compare the first window with
best, which matters when the first window is the best one or when n = k. - Treating 'y' as a vowel. The problem only counts a, e, i, o and u.
- Stopping early only when
best == kis an optional speed-up; stopping on any other condition can miss a later, better window.
Frequently asked questions
Can I return early?
Yes. A window cannot hold more than k vowels, so once best reaches k no later window can beat it and you can return k immediately.
Why is this a fixed window and not a variable one?
The length is fixed by the problem, so the left edge always moves together with the right edge. There is no condition that shrinks the window, unlike problems such as Max Consecutive Ones III.
What if k equals the length of the string?
There is only one window, the whole string, and the loop body never runs. The answer is the vowel count of the first window.