Problem 1456

Abstract / Summary

Find the highest count of vowels in any substring of a given length within a string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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
19 lines | 497 bytes | submitted September 12, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 62% (1+ million submissions).

Typical patterns to solve this problem:
  • Sliding Window
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.11 | σ = 1.13

Complexity Analysis

Time: linear
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
24 links | 14 authors | 8 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

26 solutions   September 12, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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