Count the number of subarrays having a given XOR
Given an array of integers arr[] and a number m, count the number of subarrays having XOR of their elements as m.
Examples:
Input : arr[] = {4, 2, 2, 6, 4}, m = 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}, m = 5
Output : 2
Explanation : The subarrays having XOR of
their elements as 5 are {5}
and {5, 6, 7, 8, 9}
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 m.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
long long subarrayXor( int arr[], int n, int m)
{
long long ans = 0;
for ( int i = 0; i < n; i++) {
int xorSum = 0;
for ( int j = i; j < n; j++) {
xorSum = xorSum ^ arr[j];
if (xorSum == m)
ans++;
}
}
return ans;
}
int main()
{
int arr[] = { 4, 2, 2, 6, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
int m = 6;
cout << "Number of subarrays having given XOR is "
<< subarrayXor(arr, n, m);
return 0;
}
|
Java
public class GFG {
static long subarrayXor( int arr[],
int n, int m)
{
long ans = 0 ;
for ( int i = 0 ; i < n; i++)
{
int xorSum = 0 ;
for ( int j = i; j < n; j++)
{
xorSum = xorSum ^ arr[j];
if (xorSum == m)
ans++;
}
}
return ans;
}
public static void main(String args[])
{
int [] arr = { 4 , 2 , 2 , 6 , 4 };
int n = arr.length;
int m = 6 ;
System.out.println( "Number of subarrays"
+ " having given XOR is "
+ subarrayXor(arr, n, m));
}
}
|
Python3
def subarrayXor(arr, n, m):
ans = 0
for i in range ( 0 ,n):
xorSum = 0
for j in range (i,n):
xorSum = xorSum ^ arr[j]
if (xorSum = = m):
ans + = 1
return ans
def main():
arr = [ 4 , 2 , 2 , 6 , 4 ]
n = len (arr)
m = 6
print ( "Number of subarrays having given XOR is "
, subarrayXor(arr, n, m))
if __name__ = = '__main__' :
main()
|
C#
using System;
class GFG {
static long subarrayXor( int [] arr,
int n, int m)
{
long ans = 0;
for ( int i = 0; i < n; i++)
{
int xorSum = 0;
for ( int j = i; j < n; j++)
{
xorSum = xorSum ^ arr[j];
if (xorSum == m)
ans++;
}
}
return ans;
}
public static void Main()
{
int [] arr = { 4, 2, 2, 6, 4 };
int n = arr.Length;
int m = 6;
Console.Write( "Number of subarrays"
+ " having given XOR is "
+ subarrayXor(arr, n, m));
}
}
|
PHP
<?php
function subarrayXor( $arr , $n , $m )
{
$ans = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$xorSum = 0;
for ( $j = $i ; $j < $n ; $j ++)
{
$xorSum = $xorSum ^ $arr [ $j ];
if ( $xorSum == $m )
$ans ++;
}
}
return $ans ;
}
$arr = array (4, 2, 2, 6, 4);
$n = count ( $arr );
$m = 6;
echo "Number of subarrays having given XOR is "
, subarrayXor( $arr , $n , $m );
?>
|
Javascript
<script>
function subarrayXor(arr, n, m)
{
let ans = 0;
for (let i = 0; i < n; i++)
{
let xorSum = 0;
for (let j = i; j < n; j++) {
xorSum = xorSum ^ arr[j];
if (xorSum == m)
ans++;
}
}
return ans;
}
let arr = [ 4, 2, 2, 6, 4 ];
let n = arr.length;
let m = 6;
document.write(
"Number of subarrays having given XOR is "
+ subarrayXor(arr, n, m)
);
</script>
|
Output
Number of subarrays having given XOR is 4
Time Complexity: O(n2)
Auxiliary Space: O(1)
Efficient Approach:
An Efficient Solution solves the above problem in O(n) time. Let us call the XOR of all elements in the range [i+1, j] as A, in the range [0, i] as B, and in the range [0, j] as C. If we do XOR of B with C, the overlapping elements in [0, i] from B and C zero out, and we get XOR of all elements in the range [i+1, j], i.e. A. Since A = B XOR C, we have B = A XOR C. Now, if we know the value of C and we take the value of A as m, we get the count of A as the count of all B satisfying this relation. Essentially, we get the count of all subarrays having XOR-sum m for each C. As we take the sum of this count overall C, we get our answer.
1) Initialize ans as 0.
2) Compute xorArr, the prefix xor-sum array.
3) Create a map mp in which we store count of
all prefixes with XOR as a particular value.
4) Traverse xorArr and for each element in xorArr
(A) If m^xorArr[i] XOR exists in map, then
there is another previous prefix with
same XOR, i.e., there is a subarray ending
at i with XOR equal to m. We add count of
all such subarrays to result.
(B) If xorArr[i] is equal to m, increment ans by 1.
(C) Increment count of elements having XOR-sum
xorArr[i] in map by 1.
5) Return ans.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
long long subarrayXor( int arr[], int n, int m)
{
long long ans = 0;
int * xorArr = new int [n];
unordered_map< int , int > mp;
xorArr[0] = arr[0];
for ( int i = 1; i < n; i++)
xorArr[i] = xorArr[i - 1] ^ arr[i];
for ( int i = 0; i < n; i++) {
int tmp = m ^ xorArr[i];
ans = ans + (( long long )mp[tmp]);
if (xorArr[i] == m)
ans++;
mp[xorArr[i]]++;
}
return ans;
}
int main()
{
int arr[] = { 4, 2, 2, 6, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
int m = 6;
cout << "Number of subarrays having given XOR is "
<< subarrayXor(arr, n, m);
return 0;
}
|
Java
import java.util.*;
class GFG {
static long subarrayXor( int arr[], int n, int m)
{
long ans = 0 ;
int [] xorArr = new int [n];
HashMap<Integer, Integer> mp
= new HashMap<Integer, Integer>();
xorArr[ 0 ] = arr[ 0 ];
for ( int i = 1 ; i < n; i++)
xorArr[i] = xorArr[i - 1 ] ^ arr[i];
for ( int i = 0 ; i < n; i++) {
int tmp = m ^ xorArr[i];
ans = ans
+ (mp.containsKey(tmp) == false
? 0
: (( long )mp.get(tmp)));
if (xorArr[i] == m)
ans++;
if (mp.containsKey(xorArr[i]))
mp.put(xorArr[i], mp.get(xorArr[i]) + 1 );
else
mp.put(xorArr[i], 1 );
}
return ans;
}
public static void main(String[] args)
{
int arr[] = { 4 , 2 , 2 , 6 , 4 };
int n = arr.length;
int m = 6 ;
System.out.print(
"Number of subarrays having given XOR is "
+ subarrayXor(arr, n, m));
}
}
|
Python3
def subarrayXor(arr, n, m):
ans = 0
xorArr = [ 0 for _ in range (n)]
mp = dict ()
xorArr[ 0 ] = arr[ 0 ]
for i in range ( 1 , n):
xorArr[i] = xorArr[i - 1 ] ^ arr[i]
for i in range (n):
tmp = m ^ xorArr[i]
if tmp in mp.keys():
ans = ans + (mp[tmp])
if (xorArr[i] = = m):
ans + = 1
mp[xorArr[i]] = mp.get(xorArr[i], 0 ) + 1
return ans
arr = [ 4 , 2 , 2 , 6 , 4 ]
n = len (arr)
m = 6
print ( "Number of subarrays having given XOR is" ,
subarrayXor(arr, n, m))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static long subarrayXor( int [] arr, int n, int m)
{
long ans = 0;
int [] xorArr = new int [n];
Dictionary< int , int > mp
= new Dictionary< int , int >();
xorArr[0] = arr[0];
for ( int i = 1; i < n; i++)
xorArr[i] = xorArr[i - 1] ^ arr[i];
for ( int i = 0; i < n; i++) {
int tmp = m ^ xorArr[i];
ans = ans
+ (mp.ContainsKey(tmp) == false
? 0
: (( long )mp[tmp]));
if (xorArr[i] == m)
ans++;
if (mp.ContainsKey(xorArr[i]))
mp[xorArr[i]] = mp[xorArr[i]] + 1;
else
mp.Add(xorArr[i], 1);
}
return ans;
}
public static void Main(String[] args)
{
int [] arr = { 4, 2, 2, 6, 4 };
int n = arr.Length;
int m = 6;
Console.Write(
"Number of subarrays having given XOR is "
+ subarrayXor(arr, n, m));
}
}
|
Javascript
<script>
function subarrayXor(aee,n,m)
{
let ans = 0;
let xorArr = new Array(n);
let mp = new Map();
xorArr[0] = arr[0];
for (let i = 1; i < n; i++)
xorArr[i] = xorArr[i - 1] ^ arr[i];
for (let i = 0; i < n; i++) {
let tmp = m ^ xorArr[i];
ans = ans
+ (mp.has(tmp) == false
? 0
: (mp.get(tmp)));
if (xorArr[i] == m)
ans++;
if (mp.has(xorArr[i]))
mp.set(xorArr[i], mp.get(xorArr[i]) + 1);
else
mp.set(xorArr[i], 1);
}
return ans;
}
let arr=[4, 2, 2, 6, 4];
let n = arr.length;
let m = 6;
document.write( "Number of subarrays having given XOR is "
+ subarrayXor(arr, n, m));
</script>
|
Output
Number of subarrays having given XOR is 4
Time Complexity: O(n)
Auxiliary Space: O(n)
Alternate Approach: Using Python Dictionary to store Prefix XOR
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int subarrayXor( int arr[], int n, int m)
{
unordered_map < int , int > HashTable;
HashTable[0] = 1;
int count = 0, curSum = 0;
for ( int i = 0; i < n; i++)
{
curSum ^= arr[i];
if (HashTable[curSum ^ m] > 0)
count += HashTable[curSum ^ m];
HashTable[curSum]++;
}
return (count);
}
int main()
{
int arr[] = { 5, 6, 7, 8, 9 };
int n = sizeof (arr) / sizeof (arr[0]);
int m = 5;
cout << "Number of subarrays having given XOR is " << subarrayXor(arr, n, m);
}
|
Java
import java.util.*;
class GFG
{
static int subarrayXor( int [] arr, int n, int m)
{
HashMap<Integer, Integer> HashTable
= new HashMap<>();
HashTable.put( 0 , 1 );
int count = 0 , curSum = 0 ;
for ( int i = 0 ; i < n; i++) {
curSum ^= arr[i];
if (HashTable.containsKey(curSum ^ m))
count += HashTable.get(curSum ^ m);
if (!HashTable.containsKey(curSum))
HashTable.put(curSum, 0 );
HashTable.put(curSum,
HashTable.get(curSum) + 1 );
}
return (count);
}
public static void main(String[] args)
{
int [] arr = { 5 , 6 , 7 , 8 , 9 };
int n = arr.length;
int m = 5 ;
System.out.println(
"Number of subarrays having given XOR is "
+ subarrayXor(arr, n, m));
}
}
|
Python3
from collections import defaultdict
def subarrayXor(arr, n, m):
HashTable = defaultdict( bool )
HashTable[ 0 ] = 1
count = 0
curSum = 0
for i in arr:
curSum^ = i
if HashTable[curSum^m]:
count + = HashTable[curSum^m]
HashTable[curSum] + = 1
return (count)
def main():
arr = [ 5 , 6 , 7 , 8 , 9 ]
n = len (arr)
m = 5
print ( "Number of subarrays having given XOR is "
, subarrayXor(arr, n, m))
if __name__ = = '__main__' :
main()
|
C#
using System;
using System.Collections.Generic;
using System.Collections;
public class GFG
{
public static int subarrayXor( int [] arr, int n, int m)
{
var HashTable = new Dictionary< int , int >();
HashTable[0] = 1;
var count = 0;
var curSum = 0;
for ( int i = 0; i < n; i++)
{
curSum ^= arr[i];
if (HashTable.ContainsKey(curSum ^ m))
{
count += HashTable[curSum ^ m];
}
if (!HashTable.ContainsKey(curSum))
{
HashTable[curSum] = 0;
}
HashTable[curSum] = HashTable[curSum] + 1;
}
return (count);
}
public static void Main(String[] args)
{
int [] arr = {5, 6, 7, 8, 9};
var n = arr.Length;
var m = 5;
Console.WriteLine( "Number of subarrays having given XOR is " + GFG.subarrayXor(arr, n, m).ToString());
}
}
|
Javascript
<script>
function subarrayXor(arr, n, m)
{
var HashTable = {};
HashTable[ "0" ] = 1;
var count = 0;
var curSum = 0;
for ( var i of arr)
{
curSum ^= i;
if (HashTable.hasOwnProperty((curSum ^ m).toString()))
{
count += HashTable[(curSum ^ m).toString()];
}
if (HashTable.hasOwnProperty((curSum).toString()))
HashTable[curSum.toString()] += 1;
else
HashTable[curSum.toString()] = 1;
}
return count;
}
var arr = [ 5, 6, 7, 8, 9 ] ;
var n = arr.length;
var m = 5;
console.log( "Number of subarrays having given XOR is " , subarrayXor(arr, n, m));
</script>
|
Output
Number of subarrays having given XOR is 2
Time Complexity: O(n)
Auxiliary Space: O(n)
Last Updated :
25 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...