Find Maximum Balanced XOR Subarray Length Problem
Description
LeetCode Problem 3755.
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.
Example 1:
Input: nums = [3,1,3,2,0]
Output: 4
Explanation:
The subarray [1, 3, 2, 0] has bitwise XOR 1 XOR 3 XOR 2 XOR 0 = 0 and contains 2 even and 2 odd numbers.
Example 2:
Input: nums = [3,2,8,5,4,14,9,15]
Output: 8
Explanation:
The whole array has bitwise XOR 0 and contains 4 even and 4 odd numbers.
Example 3:
Input: nums = [0]
Output: 0
Explanation:
No non-empty subarray satisfies both conditions.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Prefix State + Hash Map
A subarray has XOR 0 exactly when the prefix XOR is the same before and after it. It has equally many even and odd numbers exactly when the prefix value "evens minus odds" is the same before and after it. So describe every prefix by the pair (a, b): a is the XOR of the prefix and b is the number of evens minus the number of odds.
Scan the array and keep a hash map from each pair to the first index where it appeared (the empty prefix, pair (0, 0), is at index -1). If the current pair was seen before at index j, the subarray (j, i] is balanced, so update the answer with i - j. Otherwise store the pair with index i. Keeping only the first index gives the longest subarray.
Complexity: O(n) time and O(n) space.
class Solution:
def maxBalancedSubarray(self, nums: List[int]) -> int:
d = {(0, 0): -1}
a = b = 0
ans = 0
for i, x in enumerate(nums):
a ^= x
b += 1 if x % 2 == 0 else -1
if (a, b) in d:
ans = max(ans, i - d[(a, b)])
else:
d[(a, b)] = i
return ans