# XOR of a subarray (range of elements)

• Difficulty Level : Medium
• Last Updated : 26 Apr, 2021

Given an array arr[] of n integers and some queries. Each query is of the form (L, R), where L and R are indices of the array. Find XOR value of the subarray arr[L…R], i.e., the value which is obtained when all the elements in the range [L, R] are XORed. Assume 0-based indexing and each array element is a 32 bit unsigned integer.
Examples:

```Input : arr[] = {2, 5, 1, 6, 1, 2, 5}
L =  1, R = 4
Output : 3
The XOR value of arr[1...4] is 3.

Input : arr[] = {2, 5, 1, 6, 1, 2, 5}
L = 0, R = 6
Output : 6
The XOR value of arr[0...6] is 6.```

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Approach:
A simple solution is to traverse the given array from index L to index R for each query. This results in O(n) time complexity to process each query. If there are q queries, then total time required will be O(q*n). For large number of queries and large arrays this solution is not optimal.
An efficient solution is to first preprocess the array. Two observations will be helpful:

1. It is mentioned in the problem statement that each array element is a 32-bit unsigned number. Hence the result will also be a 32-bit unsigned number.
2. When multiple bits are XORed, the result is 1 if there are odd number of 1s, otherwise the result is 0.

Using observation 1, create a two dimensional array cnt of size 32*n. This array will be used to store count of 1s. An element cnt[i][j] represents count of number of 1s for ith bit upto index j, i.e., how many 1s are present in subarray arr[0..j] at ith bit position.
According to observation 2 to obtain XOR value, number of 1s for all 32 bit positions in the subarray arr[L…R] needs to be found. This can be done with the help of cnt array. Number of ones for ith bit position in subarray arr[L…R] is cnt[i][R] – cnt[i][L-1]. If the number of 1s for ith bit are odd, then the ith bit will be set in result. The result can then be obtained by adding power of 2 corresponding to ith bit if it is set.
Processing each query according to this algorithm will take O(32) i.e. constant time. The preprocessing stage in which cnt array is created will take O(n) time. Thus, total time complexity of this solution for q queries is O(n+q).
Implementation:

## C++

 `#include ``using` `namespace` `std;` `// Function to preprocess the array and find count of``// number of ones upto jth index for ith bit.``void` `preprocess(``int` `arr[], ``int` `n, vector >& cnt)``{``    ``int` `i, j;` `    ``// Run a loop for each bit position from``    ``// 0 to 32.``    ``for` `(i = 0; i < 32; i++) {``        ``cnt[i] = 0;``        ``for` `(j = 0; j < n; j++) {``            ``if` `(j > 0) {` `                ``// store previous count of 1s``                ``// for ith bit position.``                ``cnt[i][j] = cnt[i][j - 1];``            ``}` `            ``// Check if ith bit for jth element``            ``// of array is set or not. If it is``            ``// set then increase count of 1 for``            ``// ith bit by 1.``            ``if` `(arr[j] & (1 << i))``                ``cnt[i][j]++;``        ``}``    ``}``}` `// Function to find XOR value for a range of array elements.``int` `findXOR(``int` `L, ``int` `R, ``const` `vector > cnt)``{` `    ``// variable to store final answer.``    ``int` `ans = 0;` `    ``// variable to store number of 1s for ith bit``    ``// in the range L to R.``    ``int` `noOfOnes;` `    ``int` `i, j;` `    ``// Find number of 1s for each bit position from 0``    ``// to 32.``    ``for` `(i = 0; i < 32; i++) {``        ``noOfOnes = cnt[i][R] - ((L > 0) ? cnt[i][L - 1] : 0);` `        ``// If number of 1s are odd then in the result``        ``// ith bit will be set, i.e., 2^i will be present in``        ``// the result. Add 2^i in ans variable.``        ``if` `(noOfOnes & 1) {``            ``ans += (1 << i);``        ``}``    ``}` `    ``return` `ans;``}` `int` `main()``{``    ``int` `arr[] = { 2, 5, 1, 6, 1, 2, 5 };``    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);``    ``vector > cnt(32, vector<``int``>(n));``    ``preprocess(arr, n, cnt);``    ``int` `L = 1;``    ``int` `R = 4;``    ``cout << findXOR(L, R, cnt);``    ``return` `0;``}`

## Java

 `class` `GFG``{` `    ``// Function to preprocess the array and find count of``    ``// number of ones upto jth index for ith bit.``    ``static` `void` `preprocess(``int` `arr[], ``int` `n, ``int``[][] cnt)``    ``{``        ``int` `i, j;` `        ``// Run a loop for each bit position from``        ``// 0 to 32.``        ``for` `(i = ``0``; i < ``32``; i++)``        ``{``            ``cnt[i][``0``] = ``0``;``            ``for` `(j = ``0``; j < n; j++)``            ``{``                ``if` `(j > ``0``)``                ``{` `                    ``// store previous count of 1s``                    ``// for ith bit position.``                    ``cnt[i][j] = cnt[i][j - ``1``];``                ``}` `                ``// Check if ith bit for jth element``                ``// of array is set or not. If it is``                ``// set then increase count of 1 for``                ``// ith bit by 1.``                ``if` `((arr[j] & (``1` `<< i)) >= ``1``)``                    ``cnt[i][j]++;``            ``}``        ``}``    ``}` `    ``// Function to find XOR value for a range of array elements.``    ``static` `int` `findXOR(``int` `L, ``int` `R, ``int``[][] cnt)``    ``{` `        ``// variable to store final answer.``        ``int` `ans = ``0``;` `        ``// variable to store number of 1s for ith bit``        ``// in the range L to R.``        ``int` `noOfOnes;` `        ``int` `i, j;` `        ``// Find number of 1s for each bit position from 0``        ``// to 32.``        ``for` `(i = ``0``; i < ``32``; i++)``        ``{``            ``noOfOnes = cnt[i][R] - ((L > ``0``) ? cnt[i][L - ``1``] : ``0``);` `            ``// If number of 1s are odd then in the result``            ``// ith bit will be set, i.e., 2^i will be present in``            ``// the result. Add 2^i in ans variable.``            ``if` `(noOfOnes % ``2` `== ``1``)``            ``{``                ``ans += (``1` `<< i);``            ``}``        ``}` `        ``return` `ans;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr[] = { ``2``, ``5``, ``1``, ``6``, ``1``, ``2``, ``5` `};``        ``int` `n = arr.length;``        ``int``[][] cnt = ``new` `int``[``32``][n];``        ``preprocess(arr, n, cnt);``        ``int` `L = ``1``;``        ``int` `R = ``4``;``        ``System.out.print(findXOR(L, R, cnt));``    ``}``}` `// This code is contributed by Rajput-Ji`

## Python3

 `# Function to preprocess the array and``# find count of number of ones upto``# jth index for ith bit.``def` `preprocess(arr, n, cnt):` `    ``# Run a loop for each bit position``    ``# from 0 to 32.``    ``for` `i ``in` `range``(``32``):``        ``cnt[i][``0``] ``=` `0``        ``for` `j ``in` `range``(n):``            ``if` `(j > ``0``):` `                ``# store previous count of 1s``                ``# for ith bit position.``                ``cnt[i][j] ``=` `cnt[i][j ``-` `1``]` `            ``# Check if ith bit for jth element``            ``# of array is set or not. If it is``            ``# set then increase count of 1 for``            ``# ith bit by 1.``            ``if` `(arr[j] & (``1` `<< i)):``                ``cnt[i][j] ``+``=` `1` `# Function to find XOR value``# for a range of array elements.``def` `findXOR(L, R, cnt):` `    ``# variable to store final answer.``    ``ans ``=` `0` `    ``# variable to store number of 1s``    ``# for ith bit in the range L to R.``    ``noOfOnes ``=` `0` `    ``# Find number of 1s for each``    ``# bit position from 0 to 32.``    ``for` `i ``in` `range``(``32``):``        ``if` `L > ``0``:``            ``noOfOnes ``=` `cnt[i][R] ``-` `cnt[i][L ``-` `1``]``        ``else``:``            ``noOfOnes ``=` `cnt[i][R]` `        ``# If number of 1s are odd then in the result``        ``# ith bit will be set, i.e., 2^i will be``        ``# present in the result. Add 2^i in ans variable.``        ``if` `(noOfOnes & ``1``):``            ``ans ``+``=` `(``1` `<< i)` `    ``return` `ans` `# Driver Code``arr ``=` `[``2``, ``5``, ``1``, ``6``, ``1``, ``2``, ``5``]` `n ``=` `len``(arr)` `cnt ``=` `[[``0` `for` `i ``in` `range``(n)]``          ``for` `i ``in` `range``(``32``)]` `preprocess(arr, n, cnt)` `L ``=` `1``R ``=` `4``print``(findXOR(L, R, cnt))` `# This code is contributed by Mohit Kumar`

## C#

 `using` `System;` `class` `GFG``{` `    ``// Function to preprocess the array and find count of``    ``// number of ones upto jth index for ith bit.``    ``static` `void` `preprocess(``int` `[]arr, ``int` `n, ``int``[,] cnt)``    ``{``        ``int` `i, j;` `        ``// Run a loop for each bit position from``        ``// 0 to 32.``        ``for` `(i = 0; i < 32; i++)``        ``{``            ``cnt[i, 0] = 0;``            ``for` `(j = 0; j < n; j++)``            ``{``                ``if` `(j > 0)``                ``{` `                    ``// store previous count of 1s``                    ``// for ith bit position.``                    ``cnt[i, j] = cnt[i, j - 1];``                ``}` `                ``// Check if ith bit for jth element``                ``// of array is set or not. If it is``                ``// set then increase count of 1 for``                ``// ith bit by 1.``                ``if` `((arr[j] & (1 << i)) >= 1)``                    ``cnt[i, j]++;``            ``}``        ``}``    ``}` `    ``// Function to find XOR value for a range of array elements.``    ``static` `int` `findXOR(``int` `L, ``int` `R, ``int``[,] cnt)``    ``{` `        ``// variable to store readonly answer.``        ``int` `ans = 0;` `        ``// variable to store number of 1s for ith bit``        ``// in the range L to R.``        ``int` `noOfOnes;` `        ``int` `i;` `        ``// Find number of 1s for each bit position from 0``        ``// to 32.``        ``for` `(i = 0; i < 32; i++)``        ``{``            ``noOfOnes = cnt[i, R] - ((L > 0) ? cnt[i, L - 1] : 0);` `            ``// If number of 1s are odd then in the result``            ``// ith bit will be set, i.e., 2^i will be present in``            ``// the result. Add 2^i in ans variable.``            ``if` `(noOfOnes % 2 == 1)``            ``{``                ``ans += (1 << i);``            ``}``        ``}` `        ``return` `ans;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``int` `[]arr = { 2, 5, 1, 6, 1, 2, 5 };``        ``int` `n = arr.Length;``        ``int``[,] cnt = ``new` `int``[32, n];``        ``preprocess(arr, n, cnt);``        ``int` `L = 1;``        ``int` `R = 4;``        ``Console.Write(findXOR(L, R, cnt));``    ``}``}` `// This code is contributed by Rajput-Ji`

## Javascript

 ``
Output:
`3`

Time Complexity: O(n+q)
Auxiliary Space: O(n)

My Personal Notes arrow_drop_up