Queries on XOR of XORs of all subarrays
Last Updated :
27 Jul, 2022
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 }
Output : 0
2
6
For query 1, the extracted array is [1, 2] and
subarrays of the array is [1], [2], [1, 2].
So, the answer is (1) ? (2) ? (1 ? 2) = 0.
For query 2, the extracted array is [1, 2, 3] and
subarrays of the array is
[1], [2], [1, 2], [2, 3], [1, 2, 3].
So the answer is (1) ? (2) ? (3) ? (1 ? 2) ?
(2 ? 3) ? (1 ? 2 ? 3) = 2.
For query 3, the extracted array is [2, 3, 4] and
subarrays of the array is
[2], [3], [4], [2, 3], [3, 4], [2, 3, 4].
So the answer is (2) ? (3) ? (4) ? (2 ? 3) ?
(3 ? 4) ? (2 ? 3 ? 4) = 6.
Input : A[] = { 5, 8, 9, 1, 7 }, Q = 3
query1 = { 1, 3 }
query2 = { 3, 4 }
query3 = { 2, 5 }
Output : 12
0
0
First of all recall the properties of XOR,
- x ? x = 0
- If x ? y = z, then x = y ? z
Using the first property, we can say that any number x XORed even number of times will result in a 0 and odd number of times will result in x.
If we want to find XOPR of XORs all the subarrays of an array, we need to find the elements which appear odd number of times in all subarrays in total.
Let's say we have an array [1, 2, 3]. Its subarrays will be [1], [2], [3], [1, 2], [2, 3], [1, 2, 3].
- has occurred three times in total.
- has occurred four times in total.
- has occurred three times in total.
We can observe that number at ith index will have (i + 1)x(sizeofarray - i) frequency.
If an array has odd number of integers, starting from the first element, every alternate element will appear odd number of times in all subarrays in total. Therefore, the XOR of XORs of all subarrays will be XOR of the alternate elements in the arrays.
If an array has even number of integers, every element will appear even number of times in all subarrays in total. Therefore, the XOR of XORs of all subarrays will always be 0.
Traversing the array for every query is inefficient. We can store value of XORs upto every elements by XORing it with the alternate elements using recurrence
prefix_xor[i] = A[i] ? prefix_xor[i - 2]
For every query, we have starting index as l and ending index as r. If (r - l + 1) odd, answer will be prefix_xor[r] ? prefix_xor[l - 2].
Below is the implementation of this approach:
C++
// CPP Program to answer queries on XOR of XORs
// of all subarray
#include <bits/stdc++.h>
#define N 100
using namespace std;
// Output for each query
void ansQueries(int prefeven[], int prefodd[],
int l, int r)
{
// If number of element is even.
if ((r - l + 1) % 2 ==