Skip to main content
Back to problems
#1371
Medium Algorithms

Find the longest substring containing vowels in even counts

Hash Table String Bit Manipulation Prefix Sum
75.7% acceptance
Feb 25, 2026
2558
142
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.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn find_the_longest_substring(s: String) -> i32 {
    // vowels: a=0, e=1, i=2, o=3, u=4
    let vowel_mask = |c: u8| -> u32 {
      match c {
        b'a' => 1, b'e' => 2, b'i' => 4, b'o' => 8, b'u' => 16, _ => 0
      }
    };
    let mut seen = std::collections::HashMap::new();
    seen.insert(0u32, -1i32);
    let mut mask = 0u32;
    let mut ans = 0i32;
    for (i, b) in s.bytes().enumerate() {
      mask ^= vowel_mask(b);
      if let Some(&prev) = seen.get(&mask) {
        ans = ans.max(i as i32 - prev);
      } else {
        seen.insert(mask, i as i32);
      }
    }
    ans
  }
}