What is Max Vowels
Count the vowels inside every substring of length k, and return the largest count. Vowels are a, e, i, o, and u. The window moves by dropping one letter and adding one letter.
abciiidef k = 3 3
Approach
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step. L and R mark the window.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Time | O(n) | Each letter is added once and removed once. |
| Memory | O(1) | Only two counters are stored. |
Implementation
def max_vowels(s, k):
vow = set("aeiou")
cur = sum(ch in vow for ch in s[:k])
best = cur
for i in range(k, len(s)):
cur += (s[i] in vow) - (s[i - k] in vow)
best = max(best, cur)
return best