GeeksforGeeks Hard

Count Subarrays with XOR K

Count the subarrays whose elements XOR to exactly k.

arraybit-manipulationhash-table
Open on GeeksforGeeks ↗
02

Intuition

💡

XOR has the same prefix trick as sums, because XOR is its own inverse: xor(i..j) = pre[j] ⊕ pre[i−1]. A subarray XORs to k exactly when the current prefix XOR equals some earlier prefix ⊕ k. Count how many earlier prefixes equal pre ⊕ k.

03

Approach

1

Prefix XOR replaces prefix sum

Keep running pre = a[0]^…^a[i]. Subarray (j..i] has XOR pre ⊕ pre_j. We want that to equal k, i.e. pre_j == pre ⊕ k.

2

Count occurrences, don't just remember one

Unlike the longest variant, every earlier matching prefix gives a distinct subarray — so the map stores value → count and we add the whole count.

3

Seed with {0: 1}

The empty prefix has XOR 0, letting subarrays that start at index 0 be counted.

04

Solution & live demo

python
1def count_subarrays_xor_k(nums, k):
2 count = {0: 1} # prefix xor -> occurrences
3 pre = ans = 0
4 for n in nums:
5 pre ^= n
6 ans += count.get(pre ^ k, 0)
7 count[pre] = count.get(pre, 0) + 1
8 return ans
05

Edge cases

k = 0

Counts subarrays whose prefix XOR repeats — handled naturally by the same formula.

Same prefix value many times

Counter accumulates; each earlier occurrence is a separate subarray.

06

Complexity

Time
O(n)
Space
O(n)
One pass with a counting map.