Sliding Window · Fixed size

Max Vowels Visualizer

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

Count each block from scratchRecounting k letters at every start repeats the letters in the overlap.
Update the vowel countIf the letter that leaves is a vowel, subtract one. If the letter that enters is a vowel, add one.

Interactive solution

Vowel cells inside a window of length k
count vowels in the first k letters
best = that count
for each new letter:
update the count for the letter that left and the letter that entered
best = max(best, count)
return best
Step 0/0 Answer —

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

PieceCostWhy
TimeO(n)Each letter is added once and removed once.
MemoryO(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