Maximum Number of Vowels in a Substring of Given Length - Problem

Given a string s and an integer k, find the maximum number of vowel letters in any substring of s with length exactly k.

The vowel letters in English are: 'a', 'e', 'i', 'o', and 'u'.

For example, if s = "abciiidef" and k = 3, you need to examine all substrings of length 3: "abc" (1 vowel), "bci" (1 vowel), "cii" (2 vowels), "iii" (3 vowels), "iid" (2 vowels), "ide" (2 vowels), "def" (1 vowel). The maximum is 3 vowels.

This problem tests your understanding of the sliding window technique - a powerful pattern for solving substring problems efficiently!

Input & Output

example_1.py โ€” Basic Case
$ Input: s = "abciiidef", k = 3
โ€บ Output: 3
๐Ÿ’ก Note: The substring "iii" contains 3 vowels, which is the maximum possible for any substring of length 3.
example_2.py โ€” No Vowels Case
$ Input: s = "rythmx", k = 2
โ€บ Output: 0
๐Ÿ’ก Note: No substring of length 2 contains any vowels, so the maximum is 0.
example_3.py โ€” All Vowels Case
$ Input: s = "aeiouaei", k = 4
โ€บ Output: 4
๐Ÿ’ก Note: Multiple substrings contain 4 vowels: "aeio", "eiou", "ioua", "ouae", "uaei".

Constraints

  • 1 โ‰ค s.length โ‰ค 105
  • s consists of lowercase English letters
  • 1 โ‰ค k โ‰ค s.length
  • Vowels are: 'a', 'e', 'i', 'o', 'u'

Visualization

Tap to expand
Sliding Window VisualizationString: "abciiidef" (k=3)Characters:a b c i i i d e fWindow 1: [a,b,c]1 vowelWindow 2: [b,c,i]1 vowel-a +i = 1-1+1 = 1Window 3: [c,i,i]2 vowels-b +i = 1-0+1 = 2Window 4: [i,i,i]3 vowelsMaximum!๐ŸŽฏ Key Insight:Each character is visited at most twice:once when entering the window, once when leaving
Understanding the Visualization
1
Initialize Window
Count vowels in the first k characters
2
Slide Window
Move one position right, update count incrementally
3
Track Maximum
Keep track of the highest vowel count encountered
4
Continue Until End
Process all possible windows of size k
Key Takeaway
๐ŸŽฏ Key Insight: The sliding window technique transforms an O(n*k) problem into O(n) by avoiding redundant work and reusing previous calculations.
Asked in
Amazon 45 Microsoft 38 Google 32 Meta 28
78.6K Views
High Frequency
~15 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen