Workspace

Problem workspace

3 day streakD

Maximum Vowels in a Substring

MediumSliding WindowFixed windows

The challenge

Return the largest number of vowels in any substring of exactly k characters. Vowels are a, e, i, o, and u.

Lowercase English letters; 1 ≤ k ≤ n.

Example

abciiidef, k = 3 → 3, from iii.

Use the walkthrough below to inspect the input and each state change.

See Maximum vowels, step by step

Expand, shrink, and inspect the window state.

9 elements · zero-based indicesk = 3
Sliding window over 9 elementsThe current window is empty. Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.Empty window · L = 0, R = -1a0b1c2i3i4i5d6e7f8
Current windowRecorded answerOutside window
Left
0
Right
-1
Length
0
Step 01 / 18

Start with an empty window

Both boundaries move forward. Watch what enters, what leaves, and when the answer changes.

left = 0; right = −1

Answer so far

0
View exact input

Input: ["a","b","c","i","i","i","d","e","f"] · k = 3

Current window is empty.

Put it into code

Maintain the count of characters satisfying a predicate. The same template counts any chosen category within a fixed window.

Indices are zero-based. C++ uses C++17 or later.

def max_vowels(s, k):
    vowels = set("aeiou")
    count = best = 0
    for right, char in enumerate(s):
        count += char in vowels
        if right >= k:
            count -= s[right - k] in vowels
        if right >= k - 1:
            best = max(best, count)
    return best

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap