1473. Find the Longest Substring Containing Vowels in Even Counts
My accepted Python solution to LeetCode problem 1473, Find the Longest Substring Containing Vowels in Even Counts, running in 267ms.
- Difficulty: Medium
- Python
- Runtime 267ms
- Memory 20.1MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 267ms, memory 20.1MB, accepted 2025-12-29.
class Solution:
def findTheLongestSubstring(self, s: str) -> int:
# Use bitmask to track parity of vowels
# 5 vowels = 5 bits: a=0, e=1, i=2, o=3, u=4
# Time: O(n), Space: O(32) = O(1)
vowels = {'a': 0, 'e': 1, 'i': 2, 'o': 3, 'u': 4}
# first_occurrence[mask] = first index where this mask state occurs
# -1 means mask hasn't occurred (but mask=0 starts at index -1)
first_occurrence = {0: -1}
mask = 0
max_len = 0
for i, char in enumerate(s):
if char in vowels:
mask ^= (1 << vowels[char])
if mask in first_occurrence:
max_len = max(max_len, i - first_occurrence[mask])
else:
first_occurrence[mask] = i
return max_len