SDE & MLE Prep

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

Problem

Return the maximum number of vowels in any substring of s of length exactly k.

Example: s = "abciiidef", k = 3 → 3 ("iii")

Fixed window of size k: add the entering character, subtract the leaving one, track the maximum.

Complexity: O(n).

class Solution:
    def maxVowels(self, s: str, k: int) -> int:
        vowels = set("aeiou")
        cur = best = sum(c in vowels for c in s[:k])
        for i in range(k, len(s)):
            cur += (s[i] in vowels) - (s[i - k] in vowels)
            best = max(best, cur)
        return best