Number of Alternating XOR's
You are given an integer array nums and two integers target1 and target2.
Your task is to partition nums into one or more contiguous subarrays such that the bitwise XOR sum of the elements in the subarrays strictly alternates between target1 and target2, starting with target1.
Specifically, if the array is partitioned into k contiguous subarrays B1, B2, ..., Bk, then for each index i from 1 to k:
- If i is odd, the bitwise XOR sum of the elements in B_i must equal target1.
- If i is even, the bitwise XOR sum of the elements in B_i must equal target2.
Return the total number of valid ways to partition the array. Since the answer may be very large, return it modulo 109 + 7.
Example 1:
Input: nums = [2, 4, 2], target1 = 2, target2 = 4
Output: 1
Explanation: We can partition the array into three separate blocks: [2], [4], and [2]. The bitwise XOR of these individual blocks evaluates to 2, 4, and 2 respectively, which perfectly alternates starting with target1 and then target2. Any other combinations of blocks yield invalid XOR sequence values, making this the single valid partition for the array.
Example 2:
Input: nums = [6, 0], target1 = 6, target2 = 0
Output: 2
Explanation: Keeping the entire array [6, 0] together as a single block yields an XOR sum of 6, which fully satisfies the condition since a single block matching target1 is valid. Alternatively, we can split the array into two separate blocks: [6] and [0]. Their individual XOR sums are 6 and 0, which successfully alternate between target1 and target2. Since both of these partitioning strategies work, there are exactly 2 valid partitions.
Now Your Turn!
Pick the correct output for the given inputInput: nums = [8, 8, 8], target1 = 3, target2 = 5
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= nums.length <= 105
- 0 <= nums[i], target1, target2 <= 105
- target1 != target2