Problem Statement: Subarrays with XOR K
Given an array of integers nums and an integer k, your task is to find the total number of continuous subarrays whose bitwise XOR of all elements is equal to k.
Example 1
- Input:
nums = [4, 2, 2, 6, 4],k = 6 - Output:
4 - Explanation: The subarrays that satisfy the condition are:
[4, 2](4 ^ 2 = 6)[6][4, 2, 2, 6, 4](4 ^ 2 ^ 2 ^ 6 ^ 4 = 6)[2, 2, 6](2 ^ 2 ^ 6 = 6)
Example 2
- Input:
nums = [5, 6, 7, 8, 9],k = 5 - Output:
2 - Explanation: The subarrays are
[5]and[5, 6, 7, 8, 9](5 ^ 6 ^ 7 ^ 8 ^ 9 = 5).
Constraints
Intuition
A subarray is defined by its start index and end index . To find all subarrays with a specific XOR value :
- We iterate through every possible starting point from to .
- We then iterate through every possible endpoint from to .
- As we expand the window from to , we maintain a cumulative XOR value.
- If the cumulative XOR equals , we increment our counter.
Since we are manually checking every single possible range , we cover all combinations.
Algorithm
- Initialize
count = 0. - Use an outer loop () from to to fix the starting point of the subarray.
- Inside, initialize
current_xor = 0. - Use an inner loop () from to to expand the subarray.
- In each step of the inner loop, update
current_xorusing the XOR operator:current_xor ^= nums[j]. - Compare
current_xorwithk. If they are equal, incrementcount. - Return
countafter both loops complete.
c++ code
class Solution {
public:
int solve(vector<int>& nums, int k) {
int count = 0;
int n = nums.size();
for (int i = 0; i < n; i++) {
int current_xor = 0;
for (int j = i; j < n; j++) {
current_xor ^= nums[j];
if (current_xor == k) {
count++;
}
}
}
return count;
}
};Dry Run:
Array: [4, 2, 2, 6, 4]
Target XOR (k): 6
🔄 Start i = 0
├─ [4]
│ XOR = 4
│ ❌ Not Equal to 6
│
├─ [4, 2]
│ XOR = 4 ^ 2 = 6
│ ✅ Found Subarray
│ Count = 1
│
├─ [4, 2, 2]
│ XOR = 6 ^ 2 = 4
│ ❌ Not Equal to 6
│
├─ [4, 2, 2, 6]
│ XOR = 4 ^ 6 = 2
│ ❌ Not Equal to 6
│
└─ [4, 2, 2, 6, 4]
XOR = 2 ^ 4 = 6
✅ Found Subarray
Count = 2
──────────────────────────────
🔄 Start i = 1
├─ [2]
│ XOR = 2
│ ❌
│
├─ [2, 2]
│ XOR = 2 ^ 2 = 0
│ ❌
│
├─ [2, 2, 6]
│ XOR = 0 ^ 6 = 6
│ ✅ Found Subarray
│ Count = 3
│
└─ [2, 2, 6, 4]
XOR = 6 ^ 4 = 2
❌
──────────────────────────────
🔄 Start i = 2
├─ [2]
│ XOR = 2
│ ❌
│
├─ [2, 6]
│ XOR = 2 ^ 6 = 4
│ ❌
│
└─ [2, 6, 4]
XOR = 4 ^ 4 = 0
❌
──────────────────────────────
🔄 Start i = 3
├─ [6]
│ XOR = 6
│ ✅ Found Subarray
│ Count = 4
│
└─ [6, 4]
XOR = 6 ^ 4 = 2
❌
──────────────────────────────
🔄 Start i = 4
└─ [4]
XOR = 4
❌
──────────────────────────────
🎯 Matching Subarrays
✅ [4, 2]
✅ [4, 2, 2, 6, 4]
✅ [2, 2, 6]
✅ [6]
🏁 FINAL ANSWER = 4Complexity Analysis
- Time Complexity: because the nested loops explore all possible pairs of indices.
- Space Complexity: as we only store the count and the running XOR variable.
Optimal solution
The Intuition
To understand this, you need to know one key property of XOR: If a ^ b = c, then a ^ c = b.
- We maintain a running XOR total (
current_xor) as we traverse the array. - We want to find a subarray such that:
- By rearranging the XOR properties, we look for:
This means as we move through the array, at each step j, we simply check our Hash Map: "Have I seen a previous prefix XOR value equal to current_xor ^ k?" If yes, those occurrences represent valid subarrays ending at j.
The Algorithm
- Initialize: *
count = 0current_xor = 0freq = {0: 1}(This handles the case where the subarray starts from index 0).
- Iterate: For each
numinnums:current_xor ^= numtarget = current_xor ^ k- If
targetis infreq,count += freq[target] freq[current_xor]++(Store/update the current XOR frequency in the map).
- Return:
count.
#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int subarraysWithXorK(vector<int>& nums, int k) {
int count = 0;
int current_xor = 0;
// Map to store frequency of prefix XORs
unordered_map<int, int> freq;
// Base case: prefix XOR of 0 has appeared once
freq[0] = 1;
for (int num : nums) {
current_xor ^= num;
// If (current_xor ^ k) exists in the map, add its frequency
if (freq.count(current_xor ^ k)) {
count += freq[current_xor ^ k];
}
// Store the current prefix XOR in the map
freq[current_xor]++;
}
return count;
}
};Dry run

Complexity Analysis: Optimal XOR Approach
1. Time Complexity:
- Single Pass: We iterate through the array
numsexactly once. If the array has elements, the loop runs times. - Hash Map Operations: Inside the loop, we perform two main operations:
freq.count(target): Checks if the complement exists in the map.freq[current_xor]++: Updates the map with the new prefix XOR.
- Efficiency: Because we use an
unordered_map(implemented as a Hash Table), both search and insertion operations take time on average. - Calculation: .
2. Space Complexity:
- Hash Map Storage: We store the frequencies of prefix XOR values in the map.
- Worst Case: In the worst-case scenario (e.g., an array where every prefix XOR value is distinct), the map will contain entries.
- Calculation: Since the space used by the map grows linearly with the input size , the space complexity is .
Problem link:
Subarrays with XOR ‘K’ - Naukri Code 360
video reference:
