Find the Longest Substring Containing Vowels in Even Counts - Problem
Given a string s, find the longest substring where each vowel appears an even number of times.
The vowels are: 'a', 'e', 'i', 'o', and 'u'. A vowel appears an even number of times if it occurs 0, 2, 4, 6, ... times in the substring.
Example: In the string "eleetminicoworoep", the substring "leetminicoworo" has each vowel appearing an even number of times: e appears 2 times, i appears 2 times, o appears 4 times, while a and u appear 0 times each.
Goal: Return the length of the longest such substring.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "eleetminicoworoep"
โบ
Output:
13
๐ก Note:
The substring "leetminicoworo" (indices 1-13) contains: e=2, i=2, o=4, a=0, u=0. All vowels appear an even number of times.
example_2.py โ All Consonants
$
Input:
s = "bcbcbc"
โบ
Output:
6
๐ก Note:
The entire string contains no vowels, so all vowels appear 0 times (even). The answer is the length of the entire string.
example_3.py โ Single Vowel
$
Input:
s = "a"
โบ
Output:
0
๐ก Note:
The string contains only one 'a' (odd count), so there's no valid substring. The longest valid substring has length 0.
Visualization
Tap to expand
Understanding the Visualization
1
Initialize State
Start with all switches OFF (bitmask 0), record this state at position -1
2
Process Each Character
For vowels, flip the corresponding bit. For consonants, keep state unchanged
3
Check for Repeated State
If we've seen this exact switch configuration before, we found a valid substring
4
Calculate Length
Substring from previous occurrence to current position has all vowels even
Key Takeaway
๐ฏ Key Insight: Bitmask elegantly tracks vowel parity. When the same state appears twice, everything between has even vowel counts!
Time & Space Complexity
Time Complexity
O(n)
Single pass through string with O(1) hash map operations
โ Linear Growth
Space Complexity
O(min(n, 32))
Hash map stores at most 32 different bitmask states (2^5 vowels)
โก Linearithmic Space
Constraints
- 1 โค s.length โค 5 ร 104
- s contains only lowercase English letters
- Only vowels 'a', 'e', 'i', 'o', 'u' need to be tracked
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code