Number of Alternating XOR Partitions Problem
Description
LeetCode Problem 3811.
You are given an integer array nums and two distinct integers target1 and target2.
A partition of nums splits it into one or more contiguous, non-empty blocks that cover the entire array without overlap.
A partition is valid if the bitwise XOR of elements in its blocks alternates between target1 and target2, starting with target1.
Formally, for blocks b1, b2, …:
XOR(b1) = target1XOR(b2) = target2(if it exists)XOR(b3) = target1, and so on.
Return the number of valid partitions of nums, modulo 10^9 + 7.
Note: A single block is valid if its XOR equals target1.
Example 1:
Input: nums = [2,3,1,4], target1 = 1, target2 = 5
Output: 1
Explanation:
- The XOR of [2, 3] is 1, which matches target1.
- The XOR of the remaining block [1, 4] is 5, which matches target2.
- This is the only valid alternating partition, so the answer is 1.
Example 2:
Input: nums = [1,0,0], target1 = 1, target2 = 0
Output: 3
Explanation:
- The XOR of [1, 0, 0] is 1, which matches target1.
- The XOR of [1] and [0, 0] are 1 and 0, matching target1 and target2.
- The XOR of [1, 0] and [0] are 1 and 0, matching target1 and target2.
- Thus, the answer is 3.
Example 3:
Input: nums = [7], target1 = 1, target2 = 7
Output: 0
Explanation:
- The XOR of [7] is 7, which does not match target1, so no valid partition exists.
Constraints:
1 <= nums.length <= 10^50 <= nums[i], target1, target2 <= 10^5target1 != target2
Solution
Approach: Prefix XOR + Hash Maps
Let pre be the XOR of the prefix read so far. A block ending here has XOR target exactly when the earlier prefix had XOR pre ^ target.
Keep two maps: cnt1[x] counts partitions of a prefix with prefix XOR x whose last block has XOR target1, and cnt2[x] the same for target2. Start with cnt2[0] = 1 for the empty partition, which lets the first block be target1.
For each element update pre, then compute a = cnt2[pre ^ target1] (the new block is a target1 block) and b = cnt1[pre ^ target2] (it is a target2 block). The number of valid partitions of this prefix is a + b. Add a to cnt1[pre] and b to cnt2[pre], all modulo 10^9 + 7. The answer is the last value of a + b.
Complexity: Time O(n), space O(n), where n is the length of nums.
from collections import defaultdict
class Solution:
def alternatingXOR(self, nums: List[int], target1: int, target2: int) -> int:
cnt1 = defaultdict(int)
cnt2 = defaultdict(int)
cnt2[0] = 1
ans = pre = 0
mod = 10**9 + 7
for x in nums:
pre ^= x
a = cnt2[pre ^ target1]
b = cnt1[pre ^ target2]
ans = (a + b) % mod
cnt1[pre] = (cnt1[pre] + a) % mod
cnt2[pre] = (cnt2[pre] + b) % mod
return ans