Find number of subarrays having bitwise XOR equal to K using prefix XOR and hashing.
Problem Statement
Given an array of integers `arr` and an integer `k`, return the total number of subarrays having bitwise XOR of their elements equal to `k`.
Examples
Input: arr = [4, 2, 2, 6, 4], k = 6
Output: 4
Explanation: Subarrays with XOR 6: [4, 2], [4, 2, 2, 6, 4], [2, 2, 6], [6].
Input: arr = [5, 6, 7, 8, 9], k = 5
Output: 2
Explanation: Combining the input according to Count subarrays with given xor K logic yields 2.
Complexity
Time Complexity: O(N)
Space Complexity: O(N)
Hints
š” Hint 1:
Use the mathematical XOR property: if xr ^ y = k, then xr ^ k = y.
š” Hint 2:
Maintain a running prefix XOR and a hash map of prefix XOR frequencies.
š” Hint 3:
Base case: map.set(0, 1) accounts for prefix XOR of 0 at index -1.
Editorial & Approach
Problem Overview & Intuition
If the prefix XOR up to index i is xr, and we need a subarray XOR of k, we require a previous prefix XOR y such that xr ^ y = k. By XORing both sides with k, we get y = xr ^ k. A hash map provides O(1) frequency lookups.
Step-by-Step Approach
- Initialize
count = 0, currentXor = 0, map = new Map([[0, 1]]). - Iterate through
arr, updatingcurrentXor ^= num. - Compute
needed = currentXor ^ k. - If
map.has(needed), add its frequency tocount. - Increment frequency of
currentXorin the map. - Return
count.
Optimal Implementation (JavaScript)
function subarraysWithXorK(arr, k) {
let count = 0, currentXor = 0;
const map = new Map([[0, 1]]);
for (let num of arr) {
currentXor ^= num;
const needed = currentXor ^ k;
if (map.has(needed)) count += map.get(needed);
map.set(currentXor, (map.get(currentXor) || 0) + 1);
}
return count;
}
Complexity Analysis
Time Complexity
O(N) ā single pass with O(1) hash map operations.
Space Complexity
O(N) ā map of prefix XOR frequencies.
Edge Cases & Corner Traps Handled
- k is 0: counts subarrays with all duplicate bits canceling.
- No valid subarray: returns 0.