Find the Longest Substring Containing Vowels in Even Counts Problem
Description
LeetCode Problem 1371.
Given the string s, return the size of the longest substring containing each vowel an even number of times. That is, 'a', 'e', 'i', 'o', and 'u' must appear an even number of times.
Example 1:
Input: s = "eleetminicoworoep"
Output: 13
Explanation: The longest substring is "leetminicowor" which contains two each of the vowels: e, i and o and zero of the vowels: a and u.
Example 2:
Input: s = "leetcodeisgreat"
Output: 5
Explanation: The longest substring is "leetc" which contains two e's.
Example 3:
Input: s = "bcbcbc"
Output: 6
Explanation: In this case, the given string "bcbcbc" is the longest because all vowels: a, e, i, o and u appear zero times.
Constraints:
1 <= s.length <= 5 x 10^5scontains only lowercase English letters.
Solution
Approach: Prefix Parity Mask
For the answer, only whether each vowel's count is even or odd matters. Store the five parities in a 5-bit mask: bit 0 for a, bit 1 for e, bit 2 for i, bit 3 for o, bit 4 for u. Walking through s, a vowel flips its bit (mask ^= bit); other letters change nothing.
Let mask(i) be the mask of the prefix s[0..i]. The substring s[j+1..i] has each vowel's count equal to the count in the prefix up to i minus the count in the prefix up to j, and a difference is even exactly when both have the same parity. So:
s[j+1..i] has all vowels even exactly when mask(j) == mask(i).
For each i, the longest valid substring ending at i starts right after the earliest prefix with the same mask. There are only 32 masks, so keep an array first[mask] with the first position each mask was seen. Start with first[0] = -1 for the empty prefix, which allows substrings that start at index 0 (like the whole string "bcbcbc" in Example 3). Then for each i:
- if
maskhas been seen before, update the answer withi - first[mask]; - otherwise record
first[mask] = i. Never overwrite an earlier position, because the earliest one gives the longest substring.
Complexity: O(n) time and O(1) extra space (32 entries).
class Solution:
def findTheLongestSubstring(self, s: str) -> int:
bit = {"a": 1, "e": 2, "i": 4, "o": 8, "u": 16}
first = [-2] * 32 # first[mask] = earliest prefix end with this parity mask (-2: not seen)
first[0] = -1 # the empty prefix
mask = ans = 0
for i, ch in enumerate(s):
mask ^= bit.get(ch, 0) # flip the parity of this vowel
if first[mask] == -2:
first[mask] = i
else:
# Same parities after first[mask] and after i: every vowel is even in between.
ans = max(ans, i - first[mask])
return ans