Find the Longest Substring Containing Vowels in Even Counts - Problem

Given a string s, return the length of the longest substring containing each vowel ('a', 'e', 'i', 'o', 'u') an even number of times.

A substring is a contiguous sequence of characters within a string. For the substring to be valid, every vowel must appear an even number of times (including zero times).

Note: Consonants can appear any number of times and don't affect the validity of the substring.

Input & Output

Example 1 — Basic Case
$ Input: s = "eleetminicoworoep"
Output: 13
💡 Note: The longest valid substring has length 13. Using the bit manipulation approach, we track vowel parity states and find the longest substring between two positions with the same parity state for all vowels.
Example 2 — No Vowels
$ Input: s = "bcbcbc"
Output: 6
💡 Note: The entire string has no vowels, so all vowels appear 0 times (even). The full length 6 is the answer.
Example 3 — All Odd Counts
$ Input: s = "aeiou"
Output: 0
💡 Note: Each vowel appears exactly once (odd count). No valid substring exists where all vowels have even counts.

Constraints

  • 1 ≤ s.length ≤ 5 × 104
  • s consists of lowercase English letters only

Visualization

Tap to expand
Longest Substring with Vowels in Even Counts INPUT s = "eleetminicoworoep" e l e e t m i n i c o w o r o e p Vowels to Track: a e i o u Bitmask Encoding: a=bit0, e=bit1, i=bit2 o=bit3, u=bit4 State Examples: 00000 = all even (valid!) 00010 = only 'e' is odd 01010 = 'e','o' are odd Input: "eleetminicoworoep" ALGORITHM STEPS 1 Initialize Hash Map map[0] = -1 (state 0 at index -1, before start) 2 Track State with XOR XOR toggles bit for each vowel (odd/even parity) 3 Check State in Map If same state seen before: len = curr_idx - prev_idx 4 Update Maximum Track max length found Store first occurrence only Hash Map (state: index) 0: -1 2: 0 6: 3 4: 6 12: 7 ... Same state = vowels balanced between those indices FINAL RESULT Longest Valid Substring: "leetminicoworo" From index 1 to index 13 Vowel Count Verification: a: 0 (even) OK e: 2 (even) OK i: 2 (even) OK o: 2 (even) OK u: 0 (even) OK Output: 13 Key Insight: Use bitmask XOR to track parity of each vowel count. Two positions with the SAME state means the substring between them has all vowels appearing an even number of times. Hash map stores first occurrence of each state for O(n) time complexity with O(32) space. TutorialsPoint - Find the Longest Substring Containing Vowels in Even Counts | Hash Approach
Asked in
Facebook 8 Amazon 5 Microsoft 3
22.9K Views
Medium Frequency
~25 min Avg. Time
847 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