3811. Number of Alternating XOR Partitions
Description
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 109 + 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 matchestarget1. - The XOR of the remaining block
[1, 4]is 5, which matchestarget2. - 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 matchestarget1. - The XOR of
[1]and[0, 0]are 1 and 0, matchingtarget1andtarget2. - The XOR of
[1, 0]and[0]are 1 and 0, matchingtarget1andtarget2. - 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 matchtarget1, so no valid partition exists.
Β
Constraints:
1 <= nums.length <= 1050 <= nums[i], target1, target2 <= 105target1 != target2
Solutions
Solution 1: Recurrence
We define two hash tables \(\textit{cnt1}\) and \(\textit{cnt2}\), where \(\textit{cnt1}[x]\) represents the number of partition schemes where the bitwise XOR result is \(x\) and the partition ends with \(\textit{target1}\), while \(\textit{cnt2}[x]\) represents the number of partition schemes where the bitwise XOR result is \(x\) and the partition ends with \(\textit{target2}\). Initially, \(\textit{cnt2}[0] = 1\), representing an empty partition.
We use the variable \(\textit{pre}\) to record the bitwise XOR result of the current prefix, and the variable \(\textit{ans}\) to record the final answer. Then we traverse the array \(\textit{nums}\). For each element \(x\), we update \(\textit{pre}\) and calculate:
Then we update the answer:
Next, we update the hash tables:
Finally, we return \(\textit{ans}\).
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |