Count subarrays with given xor K
Pattern: Prefix sums and difference arrays
Count subarrays whose XOR is k with prefix XORs and a hash map. Since XOR undoes itself, the earlier prefix you need is prefix XOR k.
The problem
You are given an array of non-negative whole numbers and a number k. Return how many contiguous, non-empty subarrays
have a bitwise XOR (all elements combined with ^) equal to k. For example, [4, 2, 2, 6, 4] with k = 6 has 4 such
subarrays. The count can be large, so return a 64-bit number.
On the original site the problem is written a little differently, so use the link above for its exact wording. The
function name subarraysWithXorK and the return type are this guide's own.
Think first
- What is
a ^ a? What isa ^ 0? - If
P(i)is the XOR of everything up toi, how do you get the XOR of the part after positionsup toi? - Compare this with "Subarray Sum Equals K". What changes?
Hints
Brute force, and why it fails
For every start, extend the end and keep a running XOR, counting matches: O(n²). For 100,000 elements, about 5 × 10⁹ steps, which is too slow.
The key insight
Prefix XOR works exactly like prefix sums, because XOR can be "subtracted" by XOR-ing again. The partner you look up is
prefix ^ k instead of prefix - k.
Dry run
| prefix | 0 |
|---|---|
| count | 0 |
| seen | {0: 1} |
nums = [4, 2, 2, 6, 4] and k = 6. The map counts prefix XORs and starts with {0 seen once}.
The plan
seen = {0: 1}
prefix = 0
count = 0
for x in nums:
prefix = prefix XOR x
count = count + seen[prefix XOR k] # 0 if missing
seen[prefix] = seen[prefix] + 1
return count
Complexity
- Time
O(n)- Space
O(n)
One pass with average O(1) map operations, and up to n + 1 distinct prefix XORs stored.
Edge cases
k = 0: subarrays whose elements cancel out, including any single 0.- A single element equal to
kcounts as a subarray. - All elements equal, as in
[3, 3, 3, 3]withk = 3: every odd-length subarray counts, which makes 6.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public long subarraysWithXorK(int[] nums, int k) {
Map<Integer, Integer> seen = new HashMap<>(); // prefix xor -> how many times it has appeared
seen.put(0, 1); // the empty prefix
int prefix = 0;
long count = 0;
for (int x : nums) {
prefix ^= x;
count += seen.getOrDefault(prefix ^ k, 0); // earlier prefix p with p ^ prefix == k
seen.put(prefix, seen.getOrDefault(prefix, 0) + 1);
}
return count;
}
}C++
class Solution {
public:
long long subarraysWithXorK(vector<int>& nums, int k) {
unordered_map<int, int> seen; // prefix xor -> how many times it has appeared
seen[0] = 1; // the empty prefix
int prefix = 0;
long long count = 0;
for (int x : nums) {
prefix ^= x;
auto found = seen.find(prefix ^ k); // earlier prefix p with p ^ prefix == k
if (found != seen.end()) {
count += found->second;
}
seen[prefix]++;
}
return count;
}
};Python
class Solution:
def subarraysWithXorK(self, nums, k):
seen = {0: 1} # prefix xor -> how many times it has appeared; the empty prefix
prefix = 0
count = 0
for x in nums:
prefix ^= x
count += seen.get(prefix ^ k, 0) # earlier prefix p with p ^ prefix == k
seen[prefix] = seen.get(prefix, 0) + 1
return countCommon mistakes
- Looking up
prefix - kout of habit from the sum version. - Forgetting the starting
{0: 1}. - Recording the current prefix before looking up.