# XOR of a subarray in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an arr[] and some queries that are range between L to R in the array. Our task is to print the XOR of the subarray between L to R.

Let’s take an example to understand the problem,

Input − array = {1, 4, 5, 7, 2, 9} L = 1 , R = 5

Output −

Explanation − 4^5^7^2^9

• To solve this problem, we will create an array, based on the following observation,

• We will XOR multiple bits, if there are odd number of 1s, the result will be 1 otherwise the result is 0.

Now, we will create a two-dimensional array count that will store the count of 1s. The value count[i][j] is the count of number of 1s for position i-j which is the number of 1’s that are present in subarray arr[0..j] at ith position of the bit. The number of 1s for all bits of the sub-array arr[L..R] is found using the count array. Formula to find arr[L...R] = count[i][R] - count[i][L-1]. If the number of 1s is odd, then ith bit is set in result. The final result can be obtained by summing up the power of 2 corresponding to ith bit given that it is set bit.

Program to show the implementation of our solution,

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
void preProcessArray(int arr[], int n, vector<vector<int> >& cnt) {
int i, j;
for (i = 0; i < 32; i++) {
cnt[i][0] = 0;
for (j = 0; j < n; j++) {
if (j > 0) {
cnt[i][j] = cnt[i][j - 1];
}
if (arr[j] & (1 << i))
cnt[i][j]++;
}
}
}
int findXORofSubArray(int L, int R, const vector<vector<int> > count) {
int result = 0;
int noOfOnes;
int i, j;
for (i = 0; i < 32; i++) {
noOfOnes = count[i][R] - ((L > 0) ? count[i][L - 1] : 0);
if (noOfOnes & 1) {
result+=(1 << i);
}
}
return result;
}
int main(){
int arr[] = { 1, 4, 5, 7, 2, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
vector<vector<int> > count(32, vector<int>(n));
preProcessArray(arr, n, count);
int L = 1;
int R = 5;
cout<<"The XOR of SubArray: "<<findXORofSubArray(L, R, count);
return 0;
}

## Output

The XOR of SubArray: 13
Published on 17-Apr-2020 12:14:06