Skip to content
Related Articles

Related Articles

Improve Article

Sum of XOR of all subarrays

  • Difficulty Level : Hard
  • Last Updated : 27 Apr, 2021

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 the 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 a total number of sub-arrays is 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 is ‘Si‘ number of sub-arrays with ith bit set. For, ith bit, the 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 starting from an index ‘j'(where j varies between 0 to n – 1) with ith bit set in their XOR value. For, ith bit is to be set, an 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 an 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, the number of sub-arrays with an even the number of elements with ith bit set will switch to a number of sub-arrays with an odd number of elements with ith bit set.
Below is the implementation of this approach: 
 

C++




// 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;
}

Java




// Java program to find the sum of XOR
// of all subarray of the array
import java.util.*;
 
class GFG
{
    // Function to calculate the sum of XOR
    // of all subarrays
    static 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
            boolean odd = false;
     
            // 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
    public static void main(String[] args)
    {
        int arr[] = { 3, 8, 13 };
        int n = arr.length;
 
        System.out.println(findXorSum(arr, n));
    }
}
 
// This code is contributed by Rituraj Jain.

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

C#




// C# program to find the sum of XOR of
// all subarray of the array
using System;
 
class GFG
{
     
// Function to calculate the sum
// of XOR of all subarrays
static 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 = false;
 
        // 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
static void Main()
{
    int []arr = { 3, 8, 13 };
 
    int n = arr.Length;
 
    Console.WriteLine(findXorSum(arr, n));
}
}
 
// This code is contributed by mits

PHP




<?php
// PHP program to find the sum of XOR
// of all subarray of the array
 
// Function to calculate the sum of
// XOR of all subarrays
function findXorSum($arr, $n)
{
    // variable to store
    // the final sum
    $sum = 0;
 
    // multiplier
    $mul = 1;
 
    for ($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
        $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 = 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 ($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
$arr = array(3, 8, 13);
 
$n = sizeof($arr);
 
echo findXorSum($arr, $n);
 
// This code is contributed by Ryuga
?>

Javascript




<script>
 
// Javascript program to find
// the sum of XOR of
// all subarray of the array
 
// Function to calculate the sum of XOR
// of all subarrays
function findXorSum(arr, n)
{
    // variable to store
    // the final sum
    let sum = 0;
 
    // multiplier
    let mul = 1;
 
    for (let 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
        let c_odd = 0;
 
        // variable to check the status
        // of the odd-even count while
        // calculating c_odd
        let odd = 0;
 
        // loop to calculate initial
        // value of c_odd
        for (let 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 (let 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
    let arr = [ 3, 8, 13 ];
 
    let n = arr.length;
 
    document.write(findXorSum(arr, n));
 
</script>
Output: 
46

 

Time Complexity: O(N)
 




My Personal Notes arrow_drop_up
Recommended Articles
Page :