Python 1456.py
class Solution:
def maxVowels(self, s: str, k: int) -> int:
vowels = ("a", "e", "i", "o", "u")
have = 0
for c in s[:k]:
if c in vowels:
have += 1
result = have
for right in range(k, len(s)):
left = right - k
if s[left] in vowels:
have -= 1
if s[right] in vowels:
have += 1
result = max(result, have)
return result
Difficulty
and has an acceptance rate of about 62% (1+ million submissions).
Typical patterns to solve this problem:
- Sliding Window
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided Solution.maxVowels method computes the maximum number of vowel characters that appear in any contiguous substring of length k within the input string s. It employs a sliding-window technique to examine each possible window exactly once, updating a running count of vowels as the window moves from left to right.
Key Steps
Preparing the vowel collection and counting the first window
The method begins by defining a tuple containing the five lowercase English vowels. A counter have is initialized to zero, then the first k characters of s are inspected. For each character that belongs to the vowel tuple, the counter is incremented.
vowels = ("a", "e", "i", "o", "u")
have = 0
for c in s[:k]:
if c in vowels:
have += 1
Initializing the result with the first window’s count
After the initial scan, the current vowel count is stored in result, which will hold the best count found so far.
result = have
Sliding the window across the string
A for loop iterates from the index k up to the end of the string. For each step, the character that exits the window (s[left]) and the character that enters (s[right]) are examined. If the exiting character is a vowel, the counter is decremented; if the entering character is a vowel, the counter is incremented. The updated count is then compared with result, and result is updated if the new count is larger.
for right in range(k, len(s)):
left = right - k
if s[left] in vowels:
have -= 1
if s[right] in vowels:
have += 1
result = max(result, have)
Returning the final answer
When the loop finishes, result contains the maximum vowel count for any window of length k, and it is returned.
return result
Edge Cases Handled
The implementation gracefully handles several boundary conditions without additional checks. When k equals the length of s, the initial loop processes the entire string, and the subsequent sliding loop does not execute because the range range(k, len(s)) is empty; the method returns the vowel count of the whole string. If k is larger than the length of s, the slice s[:k] simply yields the whole string, and the sliding loop again has an empty range, resulting in the count of vowels in the available characters. An empty input string leads to an initial count of zero and a final return of zero, as the loops never iterate. The use of the tuple for vowels ensures that membership tests work correctly for any character, including non-alphabetic symbols, which are simply ignored.
Performance Optimizations
The algorithm achieves efficiency by maintaining a single integer have that reflects the vowel count of the current window. Instead of recomputing the count from scratch for each new window, it updates the count in constant time by adjusting for the character that leaves and the character that enters. This sliding-window approach eliminates redundant work and ensures that each character of s is examined at most twice-once when it first enters a window and once when it exits. Storing the vowel collection as a tuple provides fast membership testing, and the use of the built-in max function for result updates avoids explicit conditional branching. Overall, the method processes the input in a single pass with minimal auxiliary storage.
ELI5 - Simplified Explanation
Imagine you have a long string of colorful letter blocks and you want to find the best spot to look at a small window of them. This code is like a little robot helper designed to count how many vowels are hiding inside that window. First, the robot looks at the very beginning of the line of blocks. It checks the first few letters—however many you asked for—and counts how many are vowels. It keeps this count in its memory.
Then, the robot starts sliding its window one block to the right, just like a little train moving along the track. As it slides, one block leaves the window from the back and a new block enters from the front. If the block that just left was a vowel, the robot subtracts one from its count because that vowel is gone. If the new block that just entered is a vowel, the robot adds one to its count. After every slide, the robot checks its count to see if it has found a new record for the most vowels seen at once. It keeps doing this until it reaches the end of the line of blocks, always remembering the highest number it has seen so far.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||
|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||
| WalkCCC | Python | ||||||||
| leetcode.ca | C++ | Java | Python | Go | PHP | TS | |||
| Progiez | C++ | Java | Python | ||||||
| github | black-shadows | C++ | |||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | Python | ||||||||
| leetcode.ca | C++, Go, Java, PHP, Python, TypeScript | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| charles-wangkai | Java | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| lzl124631x | C++ | ||||||||
| suxrobGM | C# | ||||||||
| trung-hn | Python | ||||||||
| varunu28 | Java | ||||||||
| vthwang | Java |
Videos
Similar Problems
- problem 2271: Maximum White Tiles Covered by a Carpet
- problem 2379: Minimum Recolors to Get K Consecutive Black Blocks
- problem 2414: Length of the Longest Alphabetical Continuous Substring
Solved On The Same Day
- problem 724: Find Pivot Index
- problem 872: Leaf-Similar Trees
- problem 933: Number of Recent Calls
- problem 1207: Unique Number of Occurrences
- problem 1732: Find the Highest Altitude
- problem 2215: Find the Difference of Two Arrays
- problem 328: Odd Even Linked List
- problem 443: String Compression
- problem 649: Dota2 Senate
- problem 735: Asteroid Collision
- problem 875: Koko Eating Bananas
- problem 901: Online Stock Span
- problem 1161: Maximum Level Sum of a Binary Tree
- problem 1268: Search Suggestions System
- problem 1282: Group the People Given the Group Size They Belong To
- problem 1372: Longest ZigZag Path in a Binary Tree
- problem 1448: Count Good Nodes in Binary Tree
- problem 1493: Longest Subarray of 1's After Deleting One Element
- problem 1647: Minimum Deletions to Make Character Frequencies Unique
- problem 1657: Determine if Two Strings Are Close
- problem 1926: Nearest Exit from Entrance in Maze
- problem 2095: Delete the Middle Node of a Linked List
- problem 2130: Maximum Twin Sum of a Linked List
- problem 2352: Equal Row and Column Pairs
- problem 2390: Removing Stars From a String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality