Sum of XOR of all subarrays in C++


In this problem, we are given an array arr[] of n numbers. Our task is to create a program to find the sum of XOR of all subarrays of the array.

Here, we need to find all sub-arrays of the given array, and then for each subarray, we will find the xor of element and add the XOR value to the sum variable.

Let’s take an example to understand the problem,

Input: arr[] = {5, 1, 4}
Output:
Explanation: XOR of all subarrays for the array :
XOR {5} = 5
XOR {1} = 1
XOR {4} = 4
XOR {5,1} = 5^1 = 4
XOR {1, 4} = 1^4 = 5
XOR {5, 1, 4} = 5^1^4 = 0
Sum = 5 + 1 + 4 + 4 + 5 + 0 = 19

A simple method to solve this problem is using the next for loop to find all the subarrays. Then finding XOR of elements of the subarray and adding to the sum variable.

This solution is not efficient as it using nesting of loops and will have exponential time complexity.

An efficient approach to solve this problem is using the prefix array. This prefix array will store the xor of all elements of the array till i. i.e,

prefixarr[i] = arr[0]^arr[1]^ … ^arr[i].

After this, we can apply a simple formula to find XOR of elements from index i to j.

XOR(i-j) = prefixarr[j] - prefixarr[i]for i >= 0.
If i = 0, XOR(i-j) = prefixarr[j]

Using this formula we will find the XOR of all subarrays.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <iostream>
using namespace std;
int calcSubArrayXORSum(int arr[], int n) {
   int sum = 0;
   int multiplier = 1;
   for (int i = 0; i < 30; i++) {
      int oddCount = 0;
      bool isOdd = 0;
      for (int j = 0; j < n; j++) {
         if ((arr[j] & (1 << i)) > 0)
            isOdd = (!isOdd);
         if (isOdd)
            oddCount++;
      }
      for (int j = 0; j < n; j++) {
         sum += (multiplier * oddCount);
         if ((arr[j] & (1 << i)) > 0)
            oddCount = (n - j - oddCount);
      }
      multiplier *= 2;
   }
   return sum;
}
int main() {
   int arr[] = { 3, 8, 13 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"Sum of XOR of all subarrays is "<<calcSubArrayXORSum(arr, n);
   return 0;
}

Output

Sum of XOR of all subarrays is 46

Updated on: 17-Aug-2020

488 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements