[LeetCode] Number of Alternating XOR Partitions

3811. Number of Alternating XOR Partitions

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) = target1
  • XOR(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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

class Solution {
public:
int alternatingXOR(vector<int>& nums, int target1, int target2) {
int mod = 1e9 + 7, bit = 0;
unordered_map<int, long long> e, o;
long long E = 1, O = 0;
e[bit] = 1;
for(auto& n : nums) {
bit ^= n;
E = o.count(bit ^ target2) ? o[bit ^ target2] : 0, O = e.count(bit ^ target1) ? e[bit ^ target1] : 0;
o[bit] = (o[bit] + O) % mod;
e[bit] = (e[bit] + E) % mod;
}
return (O + E) % mod;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/number-of-alternating-xor-partitions/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.