Count Subarrays with given XOR
Last Updated :
26 Dec, 2024
Given an array of integers arr[] and a number k, the task is to count the number of subarrays having XOR of their elements as k.
Examples:
Input: arr[] = [4, 2, 2, 6, 4], k = 6
Output: 4
Explanation: The subarrays having XOR of their elements as 6 are [4, 2], [4, 2, 2, 6, 4], [2, 2, 6], and [6].
Input: arr[] = [5, 6, 7, 8, 9], k = 5
Output: 2
Explanation: The subarrays having XOR of their elements as 5 are [5] and [5, 6, 7, 8, 9].
[Naive Approach] Checking all Subarray - O(n^2) Time and O(1) Space
A Simple Solution is to use two loops to go through all possible subarrays of arr[] and count the number of subarrays having XOR of their elements as k.
C++
// C++ Program to count all subarrays having
// XOR of elements as given value K
#include <iostream>
#include <vector>
using namespace std;
// Function to find count of subarrays of arr
// with XOR value equals to K
int subarrayXor(vector<int>& arr, int k) {
int res = 0;
// Pick starting point i of subarrays
for (int i = 0; i < arr.size(); i++) {
int prefXOR = 0;
// Pick ending point j of subarray for each i
for (int j = i; j < arr.size(); j++) {
// calculate prefXOR if subarray arr[i...j]
prefXOR = prefXOR ^ arr[j];
// If prefXOR is equal to given value,
// increase ans by 1.
if (prefXOR == k)
res++;
}
}
return res;
}
int main() {
vector<int> arr = { 4, 2, 2, 6, 4 };
int k = 6;
cout << subarrayXor(arr, k);
return 0;
}
Java
// Java Program to count all subarrays having
// XOR of elements as given value K
class GfG {
// Function to find count of subarrays of arr
// with XOR value equals to K
static int subarrayXor(int[] arr, int k) {
int res = 0;
// Pick starting point i of subarrays
for (int i = 0; i < arr.length; i++) {
int prefXOR = 0;
// Pick ending point j of subarray for each i
for (int j = i; j < arr.length; j++) {
// calculate prefXOR for subarray arr[i ... j]
prefXOR = prefXOR ^ arr[j];
// If prefXOR is equal to given value, increase res by 1
if (prefXOR == k)
res++;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = { 4, 2, 2, 6, 4 };
int k = 6;
System.out.println(subarrayXor(arr, k));
}
}
Python
# Python Program to count all subarrays having
# XOR of elements as given value K
def subarrayXor(arr, k):
res = 0
# Pick starting point i of subarrays
for i in range(len(arr)):
prefXOR = 0
# Pick ending point j of subarray for each i
for j in range(i, len(arr)):
# calculate prefXOR for subarray arr[i ... j]
prefXOR ^= arr[j]
# If prefXOR is equal to given value, increase res by 1
if prefXOR == k:
res += 1
return res
if __name__ == "__main__":
arr = [4, 2, 2, 6, 4]
k = 6
print(subarrayXor(arr, k))
C#
// C# Program to count all subarrays having
// XOR of elements as given value K
using System;
class GfG {
// Function to find count of subarrays of arr
// with XOR value equals to K
static int subarrayXor(int[] arr, int k) {
int res = 0;
// Pick starting point i of subarrays
for (int i = 0; i < arr.Length; i++) {
int prefXOR = 0;
// Pick ending point j of subarray for each i
for (int j = i; j < arr.Length; j++) {
// calculate prefXOR for subarray arr[i ... j]
prefXOR ^= arr[j];
// If prefXOR is equal to given value, increase res by 1
if (prefXOR == k)
res++;
}
}
return res;
}
static void Main(string[] args) {
int[] arr = { 4, 2, 2, 6, 4 };
int k = 6;
Console.WriteLine(subarrayXor(arr, k));
}
}
JavaScript
// JavaScript Program to count all subarrays having
// XOR of elements as given value K
function subarrayXor(arr, k) {
let res = 0;
// Pick starting point i of subarrays
for (let i = 0; i < arr.length; i++) {
let prefXOR = 0;
// Pick ending point j of subarray for each i
for (let j = i; j < arr.length; j++) {
// calculate prefXOR for subarray arr[i ... j]
prefXOR ^= arr[j];
// If prefXOR is equal to given value, increase res by 1
if (prefXOR === k)
res++;
}
}
return res;
}
// Driver Code
const arr = [4, 2, 2, 6, 4];
const k = 6;
console.log(subarrayXor(arr, k));
[Efficient Approach] Using Hash Map and Prefix Sum - O(n) Time and O(n) Space
The idea is to use the properties of XOR. Let’s denote the XOR of all elements in the range [0, i] as A, the XOR of all elements in the range [i+1, j] as B, and the XOR of all elements in the range [0, j] as C.
From the properties of XOR: C = A ⊕ B
This implies: A = C ⊕ B
Now if we know the value of C (the XOR of the prefix up to index j) and have B (the target XOR value k), we can determine A (the XOR of the prefix up to index i) using: A = C ⊕ B
Using this relation, if a prefix sum A has already been seen earlier, it means there exists a subarray ending at j whose XOR is equal to k (B).
Step by step Approach:
- Use a hash map to store the frequency of prefix XOR values encountered so far.
- Traverse through the array and for each element at index i:
- Update prefXOR = prefXOR ⊕ arr[i].
- Check if A = prefXOR ⊕ k exists in the hash map. If it does, add the value of the hash map entry to result as it gives the count of subarrays ending at the current index that have XOR equal to k.
- If prefXOR is equal to k, increment the result directly, as this indicates the subarray arr[0, i] has XOR equal to k.
- Update the hash map to include the current prefXOR value.
C++
// C++ Program to count all subarrays having
// XOR of elements as given value K using Hash Map
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
// Function to find the count of subarrays of arr
// with XOR value equals to k
int subarrayXor(vector<int>& arr, int k) {
int res = 0;
// Create hash map that stores number of prefix arrays
// corresponding to a XOR value
unordered_map<int, int> mp;
int prefXOR = 0;
for (int val : arr) {
// Find XOR of current prefix
prefXOR ^= val;
// If prefXOR ^ k exist in mp then there is a subarray
// ending at i with XOR equal to k
res = res + mp[prefXOR ^ k];
// If this prefix subarray has XOR equal to k
if (prefXOR == k)
res++;
// Add the XOR of this subarray to the map
mp[prefXOR]++;
}
// Return total count of subarrays having XOR of
// elements as given value k
return res;
}
int main() {
vector<int> arr = { 4, 2, 2, 6, 4 };
int k = 6;
cout << subarrayXor(arr, k);
return 0;
}
Java
// Java Program to count all subarrays having
// XOR of elements as given value K using Hash Map
import java.util.HashMap;
class GfG {
// Function to find the count of subarrays of arr
// with XOR value equals to k
static int subarrayXor(int[] arr, int k) {
int res = 0;
// Create map that stores number of prefix arrays
// corresponding to a XOR value
HashMap<Integer, Integer> mp = new HashMap<>();
int prefXOR = 0;
for (int val : arr) {
// Find XOR of current prefix
prefXOR ^= val;
// If prefXOR ^ k exists in mp then there is a subarray
// ending at i with XOR equal to k
res += mp.getOrDefault(prefXOR ^ k, 0);
// If this prefix subarray has XOR equal to k
if (prefXOR == k)
res++;
// Add the XOR of this subarray to the map
mp.put(prefXOR, mp.getOrDefault(prefXOR, 0) + 1);
}
// Return total count of subarrays having XOR of
// elements as given value k
return res;
}
public static void main(String[] args) {
int[] arr = { 4, 2, 2, 6, 4 };
int k = 6;
System.out.println(subarrayXor(arr, k));
}
}
Python
# Python Program to count all subarrays having
# XOR of elements as given value K using Hash Map
def subarrayXor(arr, k):
res = 0
# Create map that stores number of prefix arrays
# corresponding to a XOR value
mp = {}
prefXOR = 0
for val in arr:
# Find XOR of current prefix
prefXOR ^= val
# If prefXOR ^ k exists in mp then there is a subarray
# ending at i with XOR equal to k
res += mp.get(prefXOR ^ k, 0)
# If this prefix subarray has XOR equal to k
if prefXOR == k:
res += 1
# Add the XOR of this subarray to the map
mp[prefXOR] = mp.get(prefXOR, 0) + 1
# Return total count of subarrays having XOR of
# elements as given value k
return res
if __name__ == "__main__":
arr = [4, 2, 2, 6, 4]
k = 6
print(subarrayXor(arr, k))
C#
// C# Program to count all subarrays having
// XOR of elements as given value K using Hash Map
using System;
using System.Collections.Generic;
class GfG {
// Function to find the count of subarrays of arr
// with XOR value equals to k
static int subarrayXor(int[] arr, int k) {
int res = 0;
// Create map that stores number of prefix arrays
// corresponding to a XOR value
Dictionary<int, int> mp = new Dictionary<int, int>();
int prefXOR = 0;
// Calculate the answer
foreach (int val in arr) {
// Find XOR of current prefix
prefXOR ^= val;
// If prefXOR ^ k exists in mp then there is a subarray
// ending at i with XOR equal to k
if (mp.ContainsKey(prefXOR ^ k))
res += mp[prefXOR ^ k];
// If this prefix subarray has XOR equal to k
if (prefXOR == k)
res++;
// Add the XOR of this subarray to the map
if (!mp.ContainsKey(prefXOR))
mp[prefXOR] = 0;
mp[prefXOR]++;
}
// Return total count of subarrays having XOR of
// elements as given value k
return res;
}
static void Main(string[] args) {
int[] arr = { 4, 2, 2, 6, 4 };
int k = 6;
Console.WriteLine(subarrayXor(arr, k));
}
}
JavaScript
// JavaScript Program to count all subarrays having
// XOR of elements as given value K using Hash Map
function subarrayXor(arr, k) {
let res = 0;
// Create map that stores number of prefix arrays
// corresponding to a XOR value
const mp = new Map();
let prefXOR = 0;
// Calculate the answer
for (const val of arr) {
// Find XOR of current prefix
prefXOR ^= val;
// If prefXOR ^ k exists in mp then there is a subarray
// ending at i with XOR equal to k
res += mp.get(prefXOR ^ k) || 0;
// If this prefix subarray has XOR equal to k
if (prefXOR === k)
res++;
// Add the XOR of this subarray to the map
mp.set(prefXOR, (mp.get(prefXOR) || 0) + 1);
}
// Return total count of subarrays having XOR of
// elements as given value k
return res;
}
// Driver Code
const arr = [4, 2, 2, 6, 4];
const k = 6;
console.log(subarrayXor(arr, k));
Similar Reads
Count all pairs with given XOR Given an array of distinct positive integers and a number x, find the number of pairs of integers in the array whose XOR is equal to x. Examples: Input : arr[] = {5, 4, 10, 15, 7, 6}, x = 5 Output : 1 Explanation : (10 ^ 15) = 5 Input : arr[] = {3, 6, 8, 10, 15, 50}, x = 5 Output : 2 Explanation : (
11 min read
Count pairs with Odd XOR Given an array of n integers. Find out number of pairs in array whose XOR is odd. Examples : Input : arr[] = { 1, 2, 3 } Output : 2 All pairs of array 1 ^ 2 = 3 1 ^ 3 = 2 2 ^ 3 = 1 Input : arr[] = { 1, 2, 3, 4 } Output : 4Recommended PracticeCount Pairs Odd XorTry It! Naive Approach: We can find pai
8 min read
Count subarrays with sum equal to its XOR value Given an array arr[] containing N elements, the task is to count the number of sub-arrays whose XOR of all the elements is equal to the sum of all the elements in the subarray. Examples: Input: arr[] = {2, 5, 4, 6} Output: 5 Explanation: All the subarrays {{2}, {5}, {4}, {6}} satisfies the above con
10 min read
Subarray with XOR less than k Given an array arr[] of n numbers and a number k. You have to write a program to find the number of subarrays with xor less than k. Examples:Â Input: arr[] = {8, 9, 10, 11, 12}, k=3Output: 3Explanation: There are 3 subarrays with XOR < 3: arr[0...1] = {8, 9} and 8 ^ 9 = 1arr[0...3] = {8, 9, 10, 1
15+ min read
Count subarrays having even Bitwise XOR Given an array arr[] of size N, the task is to count the number of subarrays from the given array whose Bitwise XOR is even. Examples: Input: arr[] = {1, 2, 3, 4}Output: 4Explanation: The subarrays having even Bitwise XOR are {{2}, {4}, {1, 2, 3}, {1, 2, 3, 4}}. Input: arr[] = {2, 4, 6}Output: 6Expl
11 min read
Count subarrays having odd Bitwise XOR Given an array arr[] of size N, the task is to count the number of subarrays from the given array having odd Bitwise XOR value. Examples: Input: arr[] = {1, 4, 7, 9, 10}Output: 8Explanation: The subarrays having odd Bitwise XOR are {1}, {1, 4}, {1, 4, 7, 9}, {1, 4, 7, 9, 10}, {7}, {9}, {4, 7}, {9, 1
11 min read
Sum of XOR of all subarrays Given an array containing N positive integers, the task is to find the sum of XOR of all sub-arrays of the array. Examples: Input : arr[] = {1, 3, 7, 9, 8, 7} Output : 128 Input : arr[] = {3, 8, 13} Output : 46 Explanation for second test-case: XOR of {3} = 3 XOR of {3, 8} = 11 XOR of {3, 8, 13} = 6
13 min read
Queries on XOR of XORs of all subarrays Given an array A of n integers, say A1, A2, A3, ..., An. You are given Q queries of the form [l, r]. The task is to find the XOR of XORs of all the subarrays of an array having elements Al, Al+1, ....., Ar. Examples: Input : A[] = { 1, 2, 3, 4, 5 }, Q = 3 q1 = { 1, 2 } q2 = { 1, 3 } q3 = { 2, 4 } Ou
10 min read
Maximize the number of subarrays with XOR as zero Given an array of N numbers. The task is to maximize the number of subarrays with XOR value zero by swapping the bits of an array element of any given subarray any number of times. Note: 1<=A[i]<=1018 Examples: Input: a[] = {6, 7, 14} Output : 2 2 subarrays are {7, 14} and {6, 7 and 14} by swa
11 min read
Count pairs with Bitwise XOR as ODD number Given an array of N integers, the task is to find the number of pairs (i, j) such that A[i] ^ A[j] is odd.Examples: Input : N = 5 A[] = { 5, 4, 7, 2, 1} Output :6 Since pair of A[] = ( 5, 4 ) = 1( 5, 7 ) = 2( 5, 2 ) = 7( 5, 1 ) = 4 ( 4, 7 ) = 3( 4, 2 ) = 6( 4, 1 ) = 5 ( 7, 2 ) = 5( 7, 1 ) = 6 ( 2, 1
9 min read