[LeetCode] Find Maximum Balanced XOR Subarray Length

3755. Find Maximum Balanced XOR Subarray Length

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int maxBalancedSubarray(vector<int>& nums) {
unordered_map<int,unordered_map<int,int>> at;
at[0][0] = -1;
int bit = 0, res = 0, cnt = 0;
for(int i = 0; i < nums.size(); i++) {
bit ^= nums[i];
if(nums[i] % 2 == 0) cnt++;
else cnt--;

if(at[bit].count(cnt)) res = max(res, i - at[bit][cnt]);
else at[bit][cnt] = i;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/find-maximum-balanced-xor-subarray-length/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.