Open In App

XOR of a subarray (range of elements)

Improve
Improve
Like Article
Like
Save
Share
Report

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.

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 <bits/stdc++.h>
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<vector<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))
                cnt[i][j]++;
        }
    }
}
 
// Function to find XOR value for a range of array elements.
int findXOR(int L, int R, const vector<vector<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 & 1) {
            ans += (1 << i);
        }
    }
 
    return ans;
}
 
int main()
{
    int arr[] = { 2, 5, 1, 6, 1, 2, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);
    vector<vector<int> > 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




<script>
 
// Function to preprocess the array and find count of
// number of ones upto jth index for ith bit.
function preprocess(arr, n, cnt)
{
    var 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))
                cnt[i][j]++;
        }
    }
}
 
// Function to find XOR value for a range of array elements.
function findXOR(L, R, cnt)
{
 
    // variable to store final answer.
    var ans = 0;
 
    // variable to store number of 1s for ith bit
    // in the range L to R.
    var noOfOnes;
 
    var 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;
}
 
var arr = [ 2, 5, 1, 6, 1, 2, 5 ];
var n = arr.length;
var cnt = Array.from( Array(32), () => Array(n));
preprocess(arr, n, cnt);
var L = 1;
var R = 4;
document.write( findXOR(L, R, cnt));
 
// This code is contributed by itsok.
</script>


Output

3

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



Last Updated : 10 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads