Sum of XOR of all subarrays

Given an array containing N positive integers, the task is to find the sum of XOR of all sub-arrays of the array.

Examples:

Input : arr[] = {1, 3, 7, 9, 8, 7}
Output : 128

Input : arr[] = {3, 8, 13}
Output : 46

Explanation for second test-case:
XOR of {3} = 3
XOR of {3, 8} = 11
XOR of {3, 8, 13} = 6
XOR of {8} = 8
XOR of {8, 13} = 5
XOR of {13} = 13

Sum = 3 + 11 + 6 + 8 + 5 + 13 = 46


Simple solution : A simple solution will be to generate all the sub-arrays and then iterate through them all to find the required XOR values and then sum them up. The time complexity of this approach will be O(n3).

Better solution : A better solution will be using a prefix array i.e. for every index ‘i’ of the array ‘arr[]’, create a prefix array to store the XOR of all the elements from left end of the array ‘arr[]’ up to the ith element of ‘arr[]’. Creating a prefix array will take a time of O(N).
Now, using this prefix array, we can find the XOR value of any sub-array in O(1) time.

We can find the XOR from index l to r using the formula:

if l is not zero 
    XOR = prefix[r] ^ prefix[l-1]
else 
    XOR = prefix[r].

After this, all we have to do is, to sum up the XOR values of all the sub-arrays.

Since, total number of sub-arrays are of the order (N2), the time-complexity of this approach will be O(N2).

Best solution : For the sake of better understanding, let’s assume any bit of an element is represented by the variable ‘i’ and the variable ‘sum’ is used to store the final sum.

The idea here is, we will try to find the number of XOR values with ith bit set. Let us suppose, there are ‘Si‘ number of sub-arrays with ith bit set. For, ith bit, sum can be updated as sum += (2i * S) .

So, the question is how to implement the above idea?

We will break the task to multiple steps. At each step, we will try to find the number of XOR values with ith bit set.
Now, we will break each step to sub-steps. In each sub-step, we will try to find the number of sub-arrays staring from an index ‘j'(where j varies between 0 to n – 1) with ith bit set in there XOR value. For, ith bit is to be set, odd number of elements of the sub-array should have there ith bit set.
For all the bits, in a variable c_odd, we will store the count of the number of sub-arrays starting from j = 0 with ith bit set in odd number of elements. Then, we will iterate through all the elements of the array updating the value of c_odd when needed. If we reach an element ‘j’ with ith bit set, we will update c_odd as c_odd = (n – j – c_odd). Its because, since we encountered a set bit, number of sub-arrays with even number of elements with ith bit set will switch to number of sub-arrays with odd number of elements with ith bit set.

Below is the implementation of this approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the sum of XOR of
// all subarray of the array
  
#include <iostream>
#include <vector>
using namespace std;
  
// Function to calculate the sum of XOR
// of all subarrays
int findXorSum(int arr[], int n)
{
    // variable to store
    // the final sum
    int sum = 0;
  
    // multiplier
    int mul = 1;
  
    for (int i = 0; i < 30; i++) {
  
        // variable to store number of
        // sub-arrays with odd number of elements
        // with ith bits starting from the first
        // element to the end of the array
        int c_odd = 0;
  
        // variable to check the status
        // of the odd-even count while
        // calculating c_odd
        bool odd = 0;
  
        // loop to calculate initial
        // value of c_odd
        for (int j = 0; j < n; j++) {
            if ((arr[j] & (1 << i)) > 0)
                odd = (!odd);
            if (odd)
                c_odd++;
        }
  
        // loop to iterate through
        // all the elements of the
        // array and update sum
        for (int j = 0; j < n; j++) {
            sum += (mul * c_odd);
  
            if ((arr[j] & (1 << i)) > 0)
                c_odd = (n - j - c_odd);
        }
  
        // updating the multiplier
        mul *= 2;
    }
  
    // returning the sum
    return sum;
}
  
// Driver Code
int main()
{
    int arr[] = { 3, 8, 13 };
  
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << findXorSum(arr, n);
  
    return 0;
}

chevron_right


Python3

# Python3 program to find the Sum of
# XOR of all subarray of the array

# Function to calculate the Sum of XOR
# of all subarrays
def findXorSum(arr, n):

# variable to store the final Sum
Sum = 0

# multiplier
mul = 1

for i in range(30):

# variable to store number of sub-arrays
# with odd number of elements with ith
# bits starting from the first element
# to the end of the array
c_odd = 0

# variable to check the status of the
# odd-even count while calculating c_odd
odd = 0

# loop to calculate initial
# value of c_odd
for j in range(n):
if ((arr[j] & (1 << i)) > 0):
odd = (~odd)
if (odd):
c_odd += 1

# loop to iterate through all the
# elements of the array and update Sum
for j in range(n):
Sum += (mul * c_odd)

if ((arr[j] & (1 << i)) > 0):
c_odd = (n – j – c_odd)

# updating the multiplier
mul *= 2

# returning the Sum
return Sum

# Driver Code
arr = [3, 8, 13]

n = len(arr)

print(findXorSum(arr, n))

# This code is contributed by Mohit Kumar

Output:

46

Time Complexity: O(N)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : mohit kumar 29