Ways to split array into two groups of same XOR value
Given an array A of n integers. The task is to count the number of ways to split given array elements into two disjoint groups, such that XOR of elements of each group is equal.
Examples:
Input : A[] = { 1, 2, 3 }
Output : 3
{(1), (2, 3)}, {(2), (1, 3)}, {(3), (1, 2)} are three ways with equal XOR value of two groups.
Input : A[] = { 5, 2, 3, 2 }
Output : 0
Let’s denote XOR between all elements in the first group as G1 and XOR between all elements in the second group as G2. Now, the following relation is always correct: G1 ⊕ G2 = A1 ⊕ A2 ⊕ …. ⊕ An.
So for G1 = G2, xor between all elements of array A is equal to 0. So, in that case, answer will be (2n – 2)/2 = (2n-1 – 1). In second case, when XOR between all elements isn’t 0, we can not split array. Answer will be 0.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int countgroup( int a[], int n)
{
int xs = 0;
for ( int i = 0; i < n; i++)
xs = xs ^ a[i];
if (xs == 0)
return (1 << (n-1)) - 1;
return 0;
}
int main()
{
int a[] = { 1, 2, 3 };
int n = sizeof (a)/ sizeof (a[0]);
cout << countgroup(a, n) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static int countgroup( int a[], int n) {
int xs = 0 ;
for ( int i = 0 ; i < n; i++)
xs = xs ^ a[i];
if (xs == 0 )
return ( 1 << (n - 1 )) - 1 ;
return 0 ;
}
public static void main(String args[]) {
int a[] = { 1 , 2 , 3 };
int n = a.length;
System.out.println(countgroup(a, n));
}
}
|
Python3
def countgroup(a, n):
xs = 0
for i in range (n):
xs = xs ^ a[i]
if xs = = 0 :
return ( 1 << (n - 1 )) - 1
return 0
a = [ 1 , 2 , 3 ]
n = len (a)
print (countgroup(a, n))
|
C#
using System;
class GFG {
static int countgroup( int [] a, int n)
{
int xs = 0;
for ( int i = 0; i < n; i++)
xs = xs ^ a[i];
if (xs == 0)
return (1 << (n - 1)) - 1;
return 0;
}
public static void Main()
{
int [] a = { 1, 2, 3 };
int n = a.Length;
Console.WriteLine(countgroup(a, n));
}
}
|
PHP
<?php
function countgroup( $a , $n )
{
$xs = 0;
for ( $i = 0; $i < $n ; $i ++)
$xs = $xs ^ $a [ $i ];
if ( $xs == 0)
return (1 << ( $n - 1)) - 1;
return 0;
}
$a = array (1, 2, 3);
$n = count ( $a );
echo countgroup( $a , $n );
?>
|
Javascript
<script>
function countgroup(a, n) {
var xs = 0;
for ( var i = 0; i < n; i++) xs = xs ^ a[i];
if (xs == 0) return (1 << (n - 1)) - 1;
}
var a = [1, 2, 3];
var n = a.length;
document.write(countgroup(a, n) + "<br>" );
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Last Updated :
28 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...