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
e l e e t m i n i c o w o r o e p0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16ABit 0EBit 1IBit 2OBit 3UBit 4Key Insight: Same Bitmask = Valid SubstringWhen bitmask repeats, the substring between has all vowels even!Example: "eleet..."Position 0: bitmask 00000 (start)Position 1: bitmask 00010 (after 'e')Position 3: bitmask 00000 (after 'ee') โ† Same as start!Substring from pos 1 to 3: "lee" has e=2 (even)
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

n
2n
โœ“ Linear Growth
Space Complexity
O(min(n, 32))

Hash map stores at most 32 different bitmask states (2^5 vowels)

n
2n
โšก 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
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
43.2K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen