Count even length subarrays having bitwise XOR equal to 0
Last Updated :
23 Jul, 2025
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 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 the Bitwise XOR of the subarray elements is 0 or not. Follow the steps below to solve the problem:
- Initialize a variable, say res to store the count of subarrays that satisfy the given condition.
- Traverse the array and generate all possible subarrays.
- For each subarray, check if the length of the subarray is even and the bitwise XOR of their elements is 0, then increment the res by 1.
- Finally, print the value of res.
Below is the implementation of the above approach:
C++
// 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);
}
C
// C program to implement
// the above approach
#include <stdio.h>
// 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]);
printf("%d\n", cntSubarr(arr, N));
}
// This code is contributed by phalashi.
Java
// 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
Python3
# 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
C#
// 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
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to count the number
// of even-length subarrays
// having Bitwise XOR equal to 0
function cntSubarr(arr, N)
{
// Stores the count of
// required subarrays
var res = 0;
// Stores prefix-XOR
// of arr[i, i+1, ...N-1]
var prefixXor = 0;
var i,j;
// Traverse the array
for (i = 0; i < N - 1;
i++) {
prefixXor = arr[i];
for (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
var arr = [2, 2, 3, 3, 6, 7, 8];
var N = arr.length;
document.write(cntSubarr(arr, N));
</script>
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:
- Initialize two arrays, say Even[] and Odd[] to store the frequency of Prefix XOR at even and odd indices of the given array respectively.
- Initialize a variable, say cntSub, to store the count of subarrays that satisfy the given condition.
- Traverse the given array and compute the Prefix Xor of the given array.
- Store the frequency of Prefix XOR at even and odd indices of the given array in the arrays Even[] and Odd[] respectively.
- Finally, print the count of all possible pairs of Even[] and Odd[] having a value greater than or equal to 2.
Below is the implementation of the above approach:
C++
// C++ program to implement
// the above approach
#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;
}
Java
// Java program to implement
// the above approach
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
Python3
# Python3 program to implement
# the above approach
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
C#
// C# program to implement
// the above approach
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
JavaScript
<script>
// Javascript program to implement
// the above approach
let M = 1000000;
// Function to get the count
// of even length subarrays
// having bitwise xor 0
function cntSubXor(arr, N)
{
// Stores prefix-xor of
// the given array
let prefixXor = 0;
// Stores prefix-xor at
// even index of the array.
let Even = Array.from({length: M}, (_, i) => 0);
// Stores prefix-xor at
// odd index of the array.
let Odd = Array.from({length: M}, (_, i) => 0);
// Stores count of subarrays
// that satisfy the condition
let cntSub = 0;
// length from 0 index
// to odd index is even
Odd[0] = 1;
// Traverse the array.
for(let i = 0; i < N; i++)
{
// Take prefix-xor
prefixXor = Math.floor(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
let arr = [ 2, 2, 3, 3, 6, 7, 8 ];
let N = arr.length;
document.write(cntSubXor(arr, N));
// This code is contributed by target_2
</script>
Time Complexity: O(N)
Auxiliary Space: O(M), where M is the maximum bitwise XOR possible in all subarrays.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem