XOR of all subarray XORs in C++


In this problem, we are given an array of n elements. Our task is to print XOR of XORs all possible subarrays (taken in order) created from elements of the array.

Let’s take an example to understand the problem,

Input − array = {1, 3, 6, 8}

Output − 0

Explanation

(1) ^ (3) ^ (6) ^ (8) ^ (1^3) ^ (3^6)^ (6^8) ^ (1^3^6) ^ (3^6^8) ^ (1^3^6^8)

To solve this problem, a simple solution could be iterating over all the subarray and find xors. But this is an inefficient approach. A better approach could be counting the frequency of each element of the array that occurred in all subarrays and using the property of xor − xor of the element even number of times is 0. Using this we will ignore all values that occur even number of times in the sub-array list, now elements with odd occurrence frequency are to be considered i.e. xor of elements that have odd occurrence frequency will give the final result.

To find the occurrence of each element of the array in its sub-arrays, we will use this formula (i+1)*(n-i).

Using this formula, we will find the frequency of occurrence of each element and then consider those elements that have an odd frequency, xor then to get the final result.

Example

Program to show the implementation of our solution,

 Live Demo

#include <iostream>
using namespace std;
   int xorSubarrayXors(int arr[], int N){
   int result = 0;
   for (int i = 0; i < N; i++){
      int freqency = (i + 1) * (N - i);
      if (freqency % 2 == 1)
         result ^= arr[i];
   }
   return result;
}
int main() {
   int arr[] = {1, 3, 6, 8};
   int N = sizeof(arr) / sizeof(arr[0]);
   cout<<"The xor of all subarray xors is : "<<xorSubarrayXors(arr, N);
   return 0;
}

Output

The xor of all subarray xors is : 0

Updated on: 20-Apr-2020

337 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements