626/670

626. Maximum Number of Vowels in a Substring of Given Length

Medium

Your function receives a lowercase string s and an integer k, and must return the largest number of vowels found in any substring of s of length exactly k.

The vowels are a, e, i, o, uy never counts. Only contiguous windows of length k are considered (there are len(s) − k + 1 of them), and the answer is the vowel count, an integer between 0 and k, not the substring itself.

Example 1:

Input: s = "azerty", k = 3

Output: 2

Explanation: The windows are "aze", "zer", "ert", "rty" with vowel counts 2, 1, 1, 0. The best is "aze" with 2.

Example 2:

Input: s = "education", k = 4

Output: 3

Explanation: "atio" packs three vowels (a, i, o); no length-4 window of "education" does better.

Example 3:

Input: s = "rhythm", k = 3

Output: 0

Explanation: The word has no a/e/i/o/u at all (y does not count), so every window scores 0.

Constraints:

  • 1 ≤ s.length ≤ 10⁵
  • s consists of lowercase English letters
  • 1 ≤ k ≤ s.length

Hints:

Counting vowels from scratch in each of the ~n windows costs O(n·k). Adjacent windows overlap in all but two characters — can you reuse the previous count?

Slide a fixed-size window: when it moves one step right, add 1 if the entering character is a vowel and subtract 1 if the leaving character was. Track the best count seen.

▶ Run checks these sample cases. Submit also runs hidden edge cases.

Input: s = "azerty", k = 3

Expected output: 2