Maximum Number of Vowels in a Substring of Given Length Problem
#1456
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1456.
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'.
Example 1:
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Example 2:
Input: s = "aeiou", k = 2
Output: 2
Explanation: Any substring of length 2 contains 2 vowels.
Example 3:
Input: s = "leetcode", k = 3
Output: 2
Explanation: "lee", "eet" and "ode" contain 2 vowels.
Constraints:
1 <= s.length <= 10^5sconsists of lowercase English letters.1 <= k <= s.length
Solution
Approach: Sliding Window
Count the vowels in the first window s[0..k-1]. Then slide the window one step at a time: the character s[i] comes in on the right and s[i - k] leaves on the left, so the count changes by at most one and we can update it in O(1) instead of recounting k characters.
The answer is the largest count over all windows. When k equals the length of s there is only the first window, and the loop does not run.
Complexity: O(n) time and O(1) extra space.
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = set("aeiou")
cnt = sum(c in vowels for c in s[:k]) # vowels in the first window
ans = cnt
for i in range(k, len(s)):
# Slide the window one step: s[i] comes in, s[i - k] goes out.
cnt += (s[i] in vowels) - (s[i - k] in vowels)
ans = max(ans, cnt)
return ans