Maximum Number of Vowels in a Substring of Given Length
The key idea
A fixed-length window of size k slides across the string one character at a time. Instead of recounting vowels for every window, keep a running count: when the window advances, add the new right character if it is a vowel and subtract the character that just left on the left. Track the maximum running count seen.
Problem
Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.
Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.
Constraints
- 1 <= s.length <= 10^5
- s consists of lowercase English letters.
- 1 <= k <= s.length
Examples
Input: s = "abciiidef", k = 3
Output: 3
Input: s = "aeiou", k = 2
Output: 2
Input: s = "leetcode", k = 3
Output: 2
Complexity
Time: O(n) Space: O(1)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization
More Sliding Window problems
- Find All Anagrams in a StringMEDIUM
- Longest Continuous Increasing SubsequenceEASY
- Longest Repeating Character ReplacementMEDIUM
- Longest Subarray of 1's After Deleting One ElementMEDIUM
- Longest Substring Without Repeating CharactersMEDIUM
- Max Consecutive Ones IIIMEDIUM
- Maximum Average Subarray IEASY
- Minimum Size Subarray SumMEDIUM
- Minimum Window SubstringHARD
- Permutation in StringMEDIUM
- Sliding Window MaximumHARD
- Substring with Concatenation of All WordsHARD