Maximum Number of Vowels in a Substring of Given Length
Given a string s and an integer k, return the maximum number of vowel letters (a, e, i, o, u) in any substring of s with length k. Slide a fixed length window of length k and adjust the vowel count when characters enter and leave.
Constraints
- 1 ≤ s.length ≤ 105
- s consists of lowercase English letters
- 1 ≤ k ≤ s.length
Example
s = "abciiidef", k = 33Explanation The substring "iii" contains 3 vowels.
Count vowels inside a window of size 3
Window "abc": 1 vowel — best so far.
What happens in this step
window = "abc" [0, 2] a = vowel → count = 1 b = not → count = 1 c = not → count = 1 1 vowel found — this is the best count so far.
Steps to visualize
- Place a window of length k and count how many vowels sit inside it.
- Record that vowel count as the best so far.
- Slide one step: if the leaving char is a vowel, decrement; if the entering char is, increment.
- Update best whenever the window vowel count improves.
- Stop when the window reaches the end of the string.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Window "abc": 1 vowel — best so far.
What happens in this step
window = "abc" [0, 2] a = vowel → count = 1 b = not → count = 1 c = not → count = 1 1 vowel found — this is the best count so far.
Solution
function maxVowels(s, k) {
if (k <= 0 || k > s.length) {
throw new Error("k must be between 1 and s.length");
}
const VOWELS = new Set(["a", "e", "i", "o", "u"]);
let count = 0;
for (let i = 0; i < k; i++) {
if (VOWELS.has(s[i])) count++;
}
let best = count;
for (let right = k; right < s.length; right++) {
const left = right - k;
if (VOWELS.has(s[right])) count++;
if (VOWELS.has(s[left])) count--;
best = Math.max(best, count);
}
return best;
}- Time
- O(n)
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
s = "abciiidef", k = 3 | 3 | example from the docstring |
s = "aeiou", k = 5 | 5 | smallest valid input: k === s.length |
s = "bcdea", k = 1 | 1 | k === 1 just checks each character |
s = "weallloveyou", k = 4 | 3 | window must slide across the whole string to find the best count |
s = "xyzxyz", k = 3 | 0 | no vowels anywhere returns 0 |
s = "aaaaa", k = 2 | 2 | all identical vowel characters |
s = "leetcode", k = 3 | 2 | larger, hand-verified case |
s = "abc", k = 5 | throws | throws when k is larger than the string |