easy

Maximum Number of Vowels in a Substring of Given Length

Find the maximum vowel count inside any substring of a fixed length k.

1. Define the problem

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

Inputs = "abciiidef", k = 3
Output3

Explanation The substring "iii" contains 3 vowels.

2. Visualize the solution

Count vowels inside a window of size 3

Count vowels inside a window of size 3
Statusinit

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.
Step 1 of 5

Steps to visualize

  1. Place a window of length k and count how many vowels sit inside it.
  2. Record that vowel count as the best so far.
  3. Slide one step: if the leaving char is a vowel, decrement; if the entering char is, increment.
  4. Update best whenever the window vowel count improves.
  5. Stop when the window reaches the end of the string.
3. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Count vowels inside a window of size 3
Statusinit

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.
Step 1 of 5
4. Solution

Solution

solution.tsTypeScript
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)
5. Test cases

Test cases

InputExpectedCovers
s = "abciiidef", k = 33example from the docstring
s = "aeiou", k = 55smallest valid input: k === s.length
s = "bcdea", k = 11k === 1 just checks each character
s = "weallloveyou", k = 43window must slide across the whole string to find the best count
s = "xyzxyz", k = 30no vowels anywhere returns 0
s = "aaaaa", k = 22all identical vowel characters
s = "leetcode", k = 32larger, hand-verified case
s = "abc", k = 5throwsthrows when k is larger than the string