Skip to main content
Back to problems
#3755
Medium Algorithms

Find maximum balanced xor subarray length

Array Hash Table Bit Manipulation Prefix Sum
50.7% acceptance
Feb 25, 2026
105
6
Given an integer array nums, return the length of the longest subarray that has a bitwise XOR of zero and contains an equal number of even and odd numbers. If no such subarray exists, return 0.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_balanced_subarray(nums: Vec<i32>) -> i32 {
    use std::collections::HashMap;
    let n = nums.len();
    // xor_prefix[i] = XOR of nums[0..i]
    // balance[i] = count_even[0..i] - count_odd[0..i]
    let mut first_seen: HashMap<(i32, i32), usize> = HashMap::new();
    let mut xor_pre = 0i32;
    let mut balance = 0i32;
    first_seen.insert((xor_pre, balance), 0);
    let mut ans = 0i32;
    for i in 0..n {
      xor_pre ^= nums[i];
      if nums[i] % 2 == 0 { balance += 1; } else { balance -= 1; }
      if let Some(&j) = first_seen.get(&(xor_pre, balance)) {
        ans = ans.max((i + 1 - j) as i32);
      } else {
        first_seen.insert((xor_pre, balance), i + 1);
      }
    }
    ans
  }
}