Maximum Number of Vowels in a Substring of Given Length - 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'.

Input & Output

Example 1 — Basic Case
$ Input: s = "abciio", k = 2
Output: 2
💡 Note: The substring "ii" contains 2 vowels, and "io" contains 2 vowels. All substrings of length 2: "ab"=1, "bc"=0, "ci"=1, "ii"=2, "io"=2. Maximum is 2.
Example 2 — All Consonants
$ Input: s = "rhythms", k = 4
Output: 0
💡 Note: No vowels in the string, so any substring of length 4 contains 0 vowels
Example 3 — All Vowels
$ Input: s = "aeiou", k = 2
Output: 2
💡 Note: Any substring of length 2 contains exactly 2 vowels: "ae", "ei", "io", "ou" all have 2 vowels

Constraints

  • 1 ≤ s.length ≤ 105
  • s consists of lowercase English letters
  • 1 ≤ k ≤ s.length

Visualization

Tap to expand
Maximum Vowels in Substring (k=3) INPUT String s = "abciiiO" a 0 b 1 c 2 i 3 i 4 o 5 Input Values s = "abciio" k = 3 Vowels: a, e, i, o, u = vowel = consonant ALGORITHM STEPS 1 Initialize Window Count vowels in first k=3 chars: "abc" = 1 2 Slide Window Right Remove left char, add right char 3 Update Count Adjust vowel count based on changes 4 Track Maximum Keep max vowels seen in any window Window positions: [abc]=1 [bci]=1 [cii]=2 [iio]=3 FINAL RESULT Best Window Found: i i o Substring "iio" at index 3-5 Contains 3 vowels OUTPUT 3 OK - Maximum! Time: O(n) Space: O(1) Key Insight: Sliding Window Technique Instead of recounting vowels for each window (O(n*k)), we slide the window by removing the leftmost character and adding the new rightmost character. This reduces time to O(n). We only need to track: current vowel count and maximum vowel count seen. TutorialsPoint - Maximum Number of Vowels in a Substring of Given Length | Sliding Window Approach
Asked in
Amazon 25 Microsoft 18 Google 15
89.0K Views
Medium Frequency
~15 min Avg. Time
1.8K 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