Count even length subarrays having bitwise XOR equal to 0

Given an array arr[] of size N, the task is to count all possible even length subarrays having bitwise XOR of subarray elements equal to 0.

Examples: 

Input: arr[] = {2, 2, 3, 3, 6, 7, 8}
Output: 3
Explanation:
Subarrays having XOR of of elements equal to 0 are: {{2, 2}, {3, 3}, {2, 2, 3, 3}}
Therefore, the required output is 3.

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

 

Naive Approach: The simplest approach is to traverse the array and generate all possible subarrays. For each subarray, check if the length of the subarray is even and if Bitwise XOR of the subarray elements is 0 or not. Follow the steps below to solve the problem:



Below is the implementation of the above approach: 

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the number
// of even-length subarrays
// having Bitwise XOR equal to 0
int cntSubarr(int arr[], int N)
{
    // Stores the count of
    // required subarrays
    int res = 0;
 
    // Stores prefix-XOR
    // of arr[i, i+1, ...N-1]
    int prefixXor = 0;
 
    // Traverse the array
    for (int i = 0; i < N - 1;
         i++) {
 
        prefixXor = arr[i];
 
        for (int j = i + 1; j < N;
             j++) {
 
            // Calculate the prefix-XOR
            // of current subarray
            prefixXor ^= arr[j];
 
            // Check if XOR of the
            // current subarray is 0
            // and length is even
            if (prefixXor == 0
                && (j - i + 1) % 2 == 0) {
                res++;
            }
        }
    }
    return res;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 2, 3, 3, 6, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntSubarr(arr, N);
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.io.*;
 
class GFG{
  
// Function to count the number
// of even-length subarrays
// having Bitwise XOR equal to 0
static int cntSubarr(int arr[], int N)
{
     
    // Stores the count of
    // required subarrays
    int res = 0;
  
    // Stores prefix-XOR
    // of arr[i, i+1, ...N-1]
    int prefixXor = 0;
  
    // Traverse the array
    for(int i = 0; i < N - 1; i++)
    {
        prefixXor = arr[i];
  
        for(int j = i + 1; j < N; j++)
        {
             
            // Calculate the prefix-XOR
            // of current subarray
            prefixXor ^= arr[j];
  
            // Check if XOR of the
            // current subarray is 0
            // and length is even
            if (prefixXor == 0 &&
               (j - i + 1) % 2 == 0)
            {
                res++;
            }
        }
    }
    return res;
}
  
// Driver Code
public static void main (String[] args)
{
    int arr[] = { 2, 2, 3, 3, 6, 7, 8 };
    int N = arr.length;
     
    System.out.println(cntSubarr(arr, N));
}
}
 
// This code is contributed by sanjoy_62
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
 
# Function to count the number
# of even-length subarrays
# having Bitwise XOR equal to 0
def cntSubarr(arr, N):
     
    # Stores the count of
    # required subarrays
    res = 0
 
    # Stores prefix-XOR
    # of arr[i, i+1, ...N-1]
    prefixXor = 0
 
    # Traverse the array
    for i in range(N - 1):
        prefixXor = arr[i]
        for j in range(i + 1, N):
 
            # Calculate the prefix-XOR
            # of current subarray
            prefixXor ^= arr[j]
 
            # Check if XOR of the
            # current subarray is 0
            # and length is even
            if (prefixXor == 0 and
               (j - i + 1) % 2 == 0):
                res += 1
                 
    return res
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 2, 2, 3, 3, 6, 7, 8 ]
    N = len(arr)
     
    print(cntSubarr(arr, N))
 
# This code is contributed by mohit kumar 29
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach 
using System;
  
class GFG{
   
// Function to count the number
// of even-length subarrays
// having Bitwise XOR equal to 0
static int cntSubarr(int[] arr, int N)
{
      
    // Stores the count of
    // required subarrays
    int res = 0;
   
    // Stores prefix-XOR
    // of arr[i, i+1, ...N-1]
    int prefixXor = 0;
   
    // Traverse the array
    for(int i = 0; i < N - 1; i++)
    {
        prefixXor = arr[i];
   
        for(int j = i + 1; j < N; j++)
        {
              
            // Calculate the prefix-XOR
            // of current subarray
            prefixXor ^= arr[j];
   
            // Check if XOR of the
            // current subarray is 0
            // and length is even
            if (prefixXor == 0 &&
               (j - i + 1) % 2 == 0)
            {
                res++;
            }
        }
    }
    return res;
}
   
// Driver Code
public static void Main ()
{
    int[] arr = { 2, 2, 3, 3, 6, 7, 8 };
    int N = arr.Length;
      
    Console.WriteLine(cntSubarr(arr, N));
}
}
 
// This code is contributed by sanjoy_62
chevron_right

Output
3

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The problem can be solved using Hashing. The idea is to store the frequency of the Prefix Xor in two separate arrays, say Odd[] and Even[], to store the frequency of the Prefix XOR of odd and even indices of the given array. Finally, print the count of all possible pairs from Even[] and Odd[] arrays having a value greater than or equal to 2. Following are the observations:

Odd Index – Odd Index = Even Length
Even Index – Even Index = Even Length

If Even[X] ≥ 2: Bitwise XOR of all the elements between two even indices of the given array must be 0 and the length of the subarray is also an even number ( Even Index – Even Index ).

If Odd[X] ≥ 2: Bitwise XOR of all the elements between two odd indices of the given array must be 0 and the length of the subarray is also an even number ( Odd Index – Odd Index ).

Follow the steps below to solve the problem:

 Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above appraoch
#include <bits/stdc++.h>
using namespace std;
#define M 1000000
 
// Function to get the count
// of even length subarrays
// having bitwise xor 0
int cntSubXor(int arr[], int N)
{
    // Stores prefix-xor of
    // the given array
    int prefixXor = 0;
 
    // Stores prefix-xor at
    // even index of the  array.
    int Even[M];
 
    // Stores prefix-xor at
    // odd index of the  array.
    int Odd[M];
 
    // Stores count of subarrays
    // that satisfy the condition
    int cntSub = 0;
 
    // length from 0 index
    // to odd index is even
    Odd[0] = 1;
 
    // Traverse the array.
    for (int i = 0; i < N; i++) {
        // Take prefix-xor
        prefixXor ^= arr[i];
 
        // If index is odd
        if (i % 2 == 1) {
 
            // Calculate pairs
            cntSub += Odd[prefixXor];
 
            // Increment prefix-xor
            // at odd index
            Odd[prefixXor]++;
        }
        else {
 
            // Calculate pairs
            cntSub += Even[prefixXor];
 
            // Increment prefix-xor
            // at odd index
            Even[prefixXor]++;
        }
    }
    return cntSub;
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 2, 3, 3, 6, 7, 8 };
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << cntSubXor(arr, N);
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above appraoch
import java.util.*;
 
class GFG{
     
static final int M =  1000000;
 
// Function to get the count
// of even length subarrays
// having bitwise xor 0
static int cntSubXor(int arr[], int N)
{
     
    // Stores prefix-xor of
    // the given array
    int prefixXor = 0;
 
    // Stores prefix-xor at
    // even index of the  array.
    int []Even = new int[M];
 
    // Stores prefix-xor at
    // odd index of the  array.
    int []Odd = new int[M];
 
    // Stores count of subarrays
    // that satisfy the condition
    int cntSub = 0;
 
    // length from 0 index
    // to odd index is even
    Odd[0] = 1;
 
    // Traverse the array.
    for(int i = 0; i < N; i++)
    {
         
        // Take prefix-xor
        prefixXor ^= arr[i];
 
        // If index is odd
        if (i % 2 == 1)
        {
             
            // Calculate pairs
            cntSub += Odd[prefixXor];
 
            // Increment prefix-xor
            // at odd index
            Odd[prefixXor]++;
        }
        else
        {
             
            // Calculate pairs
            cntSub += Even[prefixXor];
 
            // Increment prefix-xor
            // at odd index
            Even[prefixXor]++;
        }
    }
    return cntSub;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 2, 2, 3, 3, 6, 7, 8 };
    int N = arr.length;
     
    System.out.print(cntSubXor(arr, N));
}
}
 
// This code is contributed by Amit Katiyar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above appraoch
M = 1000000;
 
# Function to get the count
# of even length subarrays
# having bitwise xor 0
def cntSubXor(arr, N):
   
    # Stores prefix-xor of
    # the given array
    prefixXor = 0;
 
    # Stores prefix-xor at
    # even index of the array.
    Even =[0] * M;
 
    # Stores prefix-xor at
    # odd index of the array.
    Odd = [0] * M;
 
    # Stores count of subarrays
    # that satisfy the condition
    cntSub = 0;
 
    # length from 0 index
    # to odd index is even
    Odd[0] = 1;
 
    # Traverse the array.
    for i in range(0, N):
 
        # Take prefix-xor
        prefixXor ^= arr[i];
 
        # If index is odd
        if (i % 2 == 1):
 
            # Calculate pairs
            cntSub += Odd[prefixXor];
 
            # Increment prefix-xor
            # at odd index
            Odd[prefixXor] += 1;
        else:
 
            # Calculate pairs
            cntSub += Even[prefixXor];
 
            # Increment prefix-xor
            # at odd index
            Even[prefixXor] += 1;
 
    return cntSub;
 
# Driver Code
if __name__ == '__main__':
   
    arr = [2, 2, 3, 3,
           6, 7, 8];
    N = len(arr);
    print(cntSubXor(arr, N));
 
# This code is contributed by gauravrajput1
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above appraoch
using System;
 
class GFG{
     
static readonly int M =  1000000;
 
// Function to get the count
// of even length subarrays
// having bitwise xor 0
static int cntSubXor(int []arr, int N)
{
     
    // Stores prefix-xor of
    // the given array
    int prefixXor = 0;
 
    // Stores prefix-xor at
    // even index of the  array.
    int []Even = new int[M];
 
    // Stores prefix-xor at
    // odd index of the  array.
    int []Odd = new int[M];
 
    // Stores count of subarrays
    // that satisfy the condition
    int cntSub = 0;
 
    // length from 0 index
    // to odd index is even
    Odd[0] = 1;
 
    // Traverse the array.
    for(int i = 0; i < N; i++)
    {
         
        // Take prefix-xor
        prefixXor ^= arr[i];
 
        // If index is odd
        if (i % 2 == 1)
        {
             
            // Calculate pairs
            cntSub += Odd[prefixXor];
 
            // Increment prefix-xor
            // at odd index
            Odd[prefixXor]++;
        }
        else
        {
             
            // Calculate pairs
            cntSub += Even[prefixXor];
 
            // Increment prefix-xor
            // at odd index
            Even[prefixXor]++;
        }
    }
    return cntSub;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 2, 2, 3, 3, 6, 7, 8 };
    int N = arr.Length;
     
    Console.Write(cntSubXor(arr, N));
}
}
 
// This code is contributed by gauravrajput1
chevron_right

Output
3

Time Complexity: O(N)
Auxiliary Space: O(M), where M is the maximum bitwise XOR possible in all subarrays.

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.




Recommended Posts:


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.



Article Tags :