Python 1371.py
class Solution:
def findTheLongestSubstring(self, s: str) -> int:
result = 0 # empty string has an even number of vowels
# position of vowels in our state "have"
mapping = { "a": 0, "e": 1, "i": 2, "o": 3, "u": 4 }
have = [ 0, 0, 0, 0, 0 ] # number of vowels a/e/i/o/u
state = 0
first = { state: -1 } # before the first characters we have zero vowels
for i, c in enumerate(s):
# new vowel
if c in mapping:
# update counter
have[mapping[c]] += 1
# update state
state = 0
# merge lowest bits (0 if even)
for h in have:
state <<= 1
state |= h & 1
# first time we encounter this state
if state not in first:
first[state] = i
# find longest substring which starts and end with the same state
# => inbetween those we have an even number of each vowel
distance = i - first[state]
result = max(result, distance)
return result
Difficulty
and has an acceptance rate of about 76% (100k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Hash Table
- Prefix Sum
- 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 implementation computes the length of the longest substring of a given string in which each of the five English vowels appears an even number of times. It does this by converting the parity of vowel counts into a compact integer “state” and tracking the earliest index where each state occurs. The difference between the current index and the earliest index for the same state yields a candidate substring length, and the maximum of those candidates is returned.
Key Steps
Initialization
The algorithm begins by establishing several structures that support the subsequent scan of the input string.
result = 0
mapping = { "a": 0, "e": 1, "i": 2, "o": 3, "u": 4 }
have = [ 0, 0, 0, 0, 0 ]
state = 0
first = { state: -1 }
result holds the best length found so far. mapping translates each vowel to an index in the have list, which records the cumulative count of each vowel. state is an integer whose binary representation encodes the parity (even = 0, odd = 1) of the five vowel counters. first maps each observed state to the earliest index at which it appeared; the initial entry records the virtual position before any characters are processed.
Iteration and State Update
The core loop walks through the characters of the input string, updating counters and the parity state whenever a vowel is encountered.
for i, c in enumerate(s):
if c in mapping:
have[mapping[c]] += 1
state = 0
for h in have:
state <<= 1
state |= h & 1
if state not in first:
first[state] = i
When the current character c is a vowel, the corresponding entry in have is incremented. The algorithm then rebuilds state from scratch: it left-shifts the accumulator and OR-s in the least-significant bit of each counter (h & 1). This process yields a five-bit integer where each bit reflects whether the associated vowel count is odd (1) or even (0). If this newly formed state has not been seen before, the current index i is recorded as its first occurrence.
Distance Calculation
Regardless of whether the character is a vowel, the algorithm evaluates the length of the substring that would result from matching the current state with its earliest occurrence.
distance = i - first[state]
result = max(result, distance)
The subtraction yields the number of characters between the current position and the first index where the same parity pattern was observed. Because the parity of all vowels is identical at both ends, the substring bounded by those positions contains an even count of each vowel. result is updated if this distance exceeds the previously recorded maximum.
Return Value
After processing the entire string, the function returns the longest length found.
return result
Edge Cases Handled
The implementation gracefully manages several boundary conditions without special-case code. An empty input string results in the initial result value of 0, reflecting that no characters satisfy the even-vowel requirement. Strings that contain no vowels never alter the state; the dictionary entry {0: -1} remains the only state, and the distance calculation correctly yields the full length of the string as a valid substring. When a vowel appears an odd number of times, the corresponding bit in state toggles, ensuring that only substrings with matching parity patterns are considered. Repeated occurrences of the same state are handled by retaining only the earliest index in first, which guarantees that the longest possible span for that state is measured.
Performance Optimizations
The algorithm employs several techniques that keep the execution efficient. By representing the parity of all five vowel counters as a single integer, it reduces the comparison of complex structures to a simple dictionary lookup keyed by an integer. The use of a pre-computed mapping dictionary provides constant-time translation from character to counter index, avoiding repeated conditional checks. Updating the state via bitwise operations (<<= and |=) is computationally cheap and leverages the fact that only the lowest bit of each counter matters for parity. Storing only the first occurrence of each state eliminates the need to track multiple indices, thereby limiting the size of the first dictionary to at most (2^5 = 32) entries. The single pass over the input string ensures that the work scales linearly with the length of the string, while the compact data structures keep memory usage modest.
ELI5 - Simplified Explanation
Imagine you are playing a game where you collect special letter cards called vowels. These are the letters a, e, i, o, and u. You want to walk along a string of letters and pick them up one by one while keeping a secret tally of how many of each you have found.
The code works like a little helper keeping track of your collection. It uses a special trick to decide if the number of vowels you have collected so far is even or odd. Think of it like a light switch for each vowel. If the switch is off, you have an even number, and if it is on, you have an odd number.
As the code looks at each letter in the string, it updates the switches. Every time it finishes looking at a letter, it checks its memory to see if it has seen this exact same pattern of switches before. If it has seen this pattern, it means that every vowel in the section between those two points must have been collected an even number of times because the switches did not change their overall state.
The magic happens when the code measures the distance between the first time it saw that pattern and now. It keeps track of the longest distance it finds during the whole trip. This allows it to find the biggest puzzle piece in the string where all the vowels are perfectly balanced.
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 | C++ | Java | Python | ||||
| leetcode.ca | C++ | Java | Python | Go | TS | ||
| Progiez | C++ | Java | Python | ||||
| github | black-shadows | C++ | |||||
| charles-wangkai | Java | ||||||
| everthis | JS | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JS | ||||||
| MacJim | C++ | ||||||
| trung-hn | Python | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ | ||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||
| WalkCCC | C++, Python, Java | ||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | ||||||
| Progiez | C++, Java, Python | ||||||
| black-shadows | C++, C++ | ||||||
| charles-wangkai | Java | ||||||
| everthis | JavaScript | ||||||
| fsq | C++ | ||||||
| JoshCrozier | JavaScript | ||||||
| MacJim | C++ | ||||||
| trung-hn | Python | ||||||
| varunu28 | Java | ||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1248: Count Number of Nice Subarrays
- problem 1358: Number of Substrings Containing All Three Characters
- problem 1410: HTML Entity Parser
- problem 1481: Least Number of Unique Integers after K Removals
- problem 1600: Throne Inheritance
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