XOR of all subarray XORs | Set 1

08 Jul, 2022
Given an array of integers, we need to get the total XOR of all subarray XORs where subarray XOR can be obtained by XORing all elements of it.
Examples : 
Input : arr[] = [3, 5, 2, 4, 6]
Output : 7
Total XOR of all subarray XORs is,
(3) ^ (5) ^ (2) ^ (4) ^ (6)
(3^5) ^ (5^2) ^ (2^4) ^ (4^6)
(3^5^2) ^ (5^2^4) ^ (2^4^6)
(3^5^2^4) ^ (5^2^4^6) ^
(3^5^2^4^6) = 7     

Input : arr[] = {1, 2, 3}
Output : 2

Input : arr[] = {1, 2, 3, 4}
Output : 0
A simple solution is to generate all subarrays and compute XOR of all of them. Below is the implementation of the above idea : 
Implementation:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to get total xor of all subarray xors#include <bits/stdc++.h>using namespace std; // Returns XOR of all subarray xorsint getTotalXorOfSubarrayXors(int arr[], int N){    //  initialize result by 0 as (a xor 0 = a)    int res = 0;     // select the starting element    for (int i=0; i<N; i++)         // select the eNding element        for (int j=i; j<N; j++)             // Do XOR of elements in current subarray            for (int k=i; k<=j; k++)                res = res ^ arr[k];     return res;} // Driver code to test above methodsint main(){    int arr[] = {3, 5, 2, 4, 6};    int N = sizeof(arr) / sizeof(arr[0]);     cout << getTotalXorOfSubarrayXors(arr, N);    return 0;}
// java program to get total XOR// of all subarray xorspublic class GFG {             // Returns XOR of all subarray xors    static int getTotalXorOfSubarrayXors(                          int arr[], int N)    {                 // initialize result by        // 0 as (a xor 0 = a)        int res = 0;                 // select the starting element        for (int i = 0; i < N; i++)                     // select the eNding element            for (int j = i; j < N; j++)                     // Do XOR of elements            // in current subarray            for (int k = i; k <= j; k++)                res = res ^ arr[k];             return res;    }         // Driver code    public static void main(String args[])    {        int arr[] = {3, 5, 2, 4, 6};        int N = arr.length;                 System.out.println(            getTotalXorOfSubarrayXors(arr, N));    }} // This code is contributed by Sam007.
# python program to get total xor# of all subarray xors # Returns XOR of all subarray xorsdef getTotalXorOfSubarrayXors(arr, N):         # initialize result by 0 as    # (a xor 0 = a)    res = 0     # select the starting element    for i in range(0, N):                 # select the eNding element        for j in range(i, N):                         # Do XOR of elements in            # current subarray            for k in range(i, j + 1):                res = res ^ arr[k]                 return res # Driver code to test above methodsarr = [3, 5, 2, 4, 6]N = len(arr) print(getTotalXorOfSubarrayXors(arr, N)) # This code is contributed by Sam007.
// C# program to get total XOR// of all subarray xorsusing System; class GFG { // Returns XOR of all subarray xorsstatic int getTotalXorOfSubarrayXors(int []arr,                                     int N){     // initialize result by// 0 as (a xor 0 = a)int res = 0; // select the starting elementfor (int i = 0; i < N; i++)     // select the eNding element    for (int j = i; j < N; j++)         // Do XOR of elements        // in current subarray        for (int k = i; k <= j; k++)            res = res ^ arr[k]; return res;} // Driver Codestatic void Main(){    int []arr = {3, 5, 2, 4, 6};    int N = arr.Length;    Console.Write(getTotalXorOfSubarrayXors(arr, N));}} // This code is contributed by Sam007
<?php// PHP program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors($arr, $N){         // initialize result by    // 0 as (a xor 0 = a)    $res = 0;     // select the starting element    for($i = 0; $i < $N; $i++)         // select the eNding element        for($j = $i; $j < $N; $j++)             // Do XOR of elements in            // current subarray            for($k = $i; $k <= $j; $k++)                $res = $res ^ $arr[$k];     return $res;}     // Driver code    $arr = array(3, 5, 2, 4, 6);    $N = sizeof($arr);    echo getTotalXorOfSubarrayXors($arr, $N); // This code is contributed by nitin mittal.?>
<script> // JavaScript program for the above approach     // Returns XOR of all subarray xors    function getTotalXorOfSubarrayXors(                          arr, N)    {                 // initialize result by        // 0 as (a xor 0 = a)        let res = 0;                 // select the starting element        for (let i = 0; i < N; i++)                     // select the eNding element            for (let j = i; j < N; j++)                     // Do XOR of elements            // in current subarray            for (let k = i; k <= j; k++)                res = res ^ arr[k];             return res;    }     // Driver Code     // Both a[] and b[] must be of same size.    let arr = [3, 5, 2, 4, 6];    let N = arr.length;             document.write(getTotalXorOfSubarrayXors(arr, N)); // This code is contributed by code_hunt.</script>
7
Time Complexity: O(N3)
An efficient solution is based on the idea to enumerate all subarrays, we can count the frequency of each element that occurred totally in all subarrays, if the frequency of an element is odd then it will be included in the final result otherwise not. 
As in above example, 
3 occurred 5 times,
5 occurred 8 times,
2 occurred 9 times,
4 occurred 8 times,
6 occurred 5 times
So our final result will be xor of all elements which occurred odd number of times
i.e. 3^2^6 = 7

From above occurrence pattern we can observe that number at i-th index will have 
(i + 1) * (N - i) frequency. 
So we can iterate over all elements once and calculate their frequencies and if it is odd then we can include that in our final result by XORing it with the result. Total time complexity of the solution will be O(N) 
Implementation:
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to get total// xor of all subarray xors#include <bits/stdc++.h>using namespace std; // Returns XOR of all subarray xorsint getTotalXorOfSubarrayXors(int arr[],                              int N){    // initialize result by 0    // as (a XOR 0 = a)    int res = 0;     // loop over all elements once    for (int i = 0; i < N; i++)    {        // get the frequency of        // current element        int freq = (i + 1) * (N - i);         // Uncomment below line to print        // the frequency of arr[i]        // cout << arr[i] << " " << freq << endl;         // if frequency is odd, then        // include it in the result        if (freq % 2 == 1)            res = res ^ arr[i];    }     // return the result    return res;} // Driver Codeint main(){    int arr[] = {3, 5, 2, 4, 6};    int N = sizeof(arr) / sizeof(arr[0]);     cout << getTotalXorOfSubarrayXors(arr, N);    return 0;}
// java program to get total xor// of all subarray xorsimport java.io.*; public class GFG {         // Returns XOR of all subarray    // xors    static int getTotalXorOfSubarrayXors(                          int arr[], int N)    {                 // initialize result by 0        // as (a XOR 0 = a)        int res = 0;             // loop over all elements once        for (int i = 0; i < N; i++)        {            // get the frequency of            // current element            int freq = (i + 1) * (N - i);                 // Uncomment below line to print            // the frequency of arr[i]                         // if frequency is odd, then            // include it in the result            if (freq % 2 == 1)                res = res ^ arr[i];        }             // return the result        return res;    }         public static void main(String[] args)    {         int arr[] = {3, 5, 2, 4, 6};        int N = arr.length;        System.out.println(            getTotalXorOfSubarrayXors(arr, N));    }} // This code is contributed by Sam007.
# Python3 program to get total# xor of all subarray xors # Returns XOR of all# subarray xorsdef getTotalXorOfSubarrayXors(arr, N):     # initialize result by 0    # as (a XOR 0 = a)    res = 0     # loop over all elements once    for i in range(0, N):             # get the frequency of        # current element        freq = (i + 1) * (N - i)         # Uncomment below line to print        # the frequency of arr[i]         # if frequency is odd, then        # include it in the result        if (freq % 2 == 1):            res = res ^ arr[i]         # return the result    return res # Driver Codearr = [3, 5, 2, 4, 6]N = len(arr)print(getTotalXorOfSubarrayXors(arr, N))     # This code is contributed# by Smitha
// C# program to get total xor// of all subarray xorsusing System; class GFG{// Returns XOR of all subarray xorsstatic int getTotalXorOfSubarrayXors(int []arr,                                     int N){    // initialize result by 0    // as (a XOR 0 = a)    int res = 0;     // loop over all elements once    for (int i = 0; i < N; i++)    {        // get the frequency of        // current element        int freq = (i + 1) * (N - i);         // Uncomment below line to print        // the frequency of arr[i]                 // if frequency is odd, then        // include it in the result        if (freq % 2 == 1)            res = res ^ arr[i];    }     // return the result    return res;}         // Driver Code    public static void Main()    {    int []arr = {3, 5, 2, 4, 6};    int N = arr.Length;     Console.Write(getTotalXorOfSubarrayXors(arr, N));    }}      // This code is contributed by Sam007
<?php// PHP program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors($arr,                                   $N){         // initialize result by 0    // as (a XOR 0 = a)    $res = 0;     // loop over all elements once    for ($i = 0; $i < $N; $i++)    {                 // get the frequency of        // current element        $freq = ($i + 1) * ($N - $i);         // if frequency is odd, then        // include it in the result        if ($freq % 2 == 1)            $res = $res ^ $arr[$i];    }     // return the result    return $res;}     // Driver Code    $arr = array(3, 5, 2, 4, 6);    $N = count($arr);     echo getTotalXorOfSubarrayXors($arr, $N); // This code is contributed by anuj_67.?>
<script> // Javascript program to get total// xor of all subarray xors // Returns XOR of all subarray xorsfunction getTotalXorOfSubarrayXors(arr, N){    // initialize result by 0    // as (a XOR 0 = a)    let res = 0;     // loop over all elements once    for (let i = 0; i < N; i++)    {        // get the frequency of        // current element        let freq = (i + 1) * (N - i);         // Uncomment below line to print        // the frequency of arr[i]        // cout << arr[i] << " " << freq << endl;         // if frequency is odd, then        // include it in the result        if (freq % 2 == 1)            res = res ^ arr[i];    }     // return the result    return res;} // Driver Code    let arr = [3, 5, 2, 4, 6];    let N = arr.length;     document.write(getTotalXorOfSubarrayXors(arr, N)); </script>
7
Time Complexity : O(N)
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. 
Sam007
vt_m
nitin mittal
Smitha Dinesh Semwal
nidhi_biet
code_hunt
rishavmahato348
hardikkoriintern
Amazon
Bitwise-XOR
subarray
Arrays
Mathematical
Amazon
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.