Maximum Number of Vowels in a Substring
Medium · Sliding Window · String · Sliding Window
Problem
Given a string s of lowercase letters and a whole number k, return the largest number of vowels in any substring of s of length exactly k.
The vowels are a, e, i, o and u.
Examples
Input: s = "abcdeiou", k = 3 Output: 3
The window "eio" (and also "iou") is all vowels.
Input: s = "xyz", k = 2 Output: 0
The string has no vowels at all.
Input: s = "rhythm", k = 1 Output: 0
y is not a vowel here, so no single letter is one.
Constraints
- 1 <= len(s) <= 10^5
- s consists of lowercase English letters
- 1 <= k <= len(s)
Approaches
- Recount every window — time O(n · k), space O(1)
Follow-up
What if the window could be any length and you wanted the longest one with at most k consonants? Then the window grows and shrinks instead of sliding at a fixed width; see the first use case.
Related problems
Start free on Cariara · Coding problems · System design studio