Leetcode #1456: Maximum Number of Vowels in a Substring of Given Length
In this guide, we solve Leetcode #1456 Maximum Number of Vowels in a Substring of Given Length in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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'.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: String, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: s = "abciiidef", k = 3
Output: 3
Explanation: The substring "iii" contains 3 vowel letters.
Python Solution
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = set("aeiou")
ans = cnt = sum(c in vowels for c in s[:k])
for i in range(k, len(s)):
cnt += int(s[i] in vowels) - int(s[i - k] in vowels)
ans = max(ans, cnt)
return ans
Complexity
The time complexity is , where is the length of the string . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.