Check if the array has an element which is equal to XOR of remaining elements
Given an array arr[] of N elements, the task is to check if the array has an element which is equal to the XOR of all the remaining elements.
Examples:
Input: arr[] = { 8, 2, 4, 15, 1 }
Output: Yes
8 is the required element as 2 ^ 4 ^ 15 ^ 1 = 8.
Input: arr[] = {4, 2, 3}
Output: No
Approach: First, take the XOR of all the elements of the array and store it in a variable xorArr. Now traverse the complete array again and for every element, calculate the xor of the array elements excluding the current element arr[i] i.e. x = xorArr ^ arr[i].
If x = arr[i] then arr[i] is the required element and hence print Yes. If no such element is found then print No.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool containsElement( int arr[], int n)
{
int xorArr = 0;
for ( int i = 0; i < n; ++i)
xorArr ^= arr[i];
for ( int i = 0; i < n; ++i) {
int x = xorArr ^ arr[i];
if (arr[i] == x)
return true ;
}
return false ;
}
int main()
{
int arr[] = { 8, 2, 4, 15, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
if (containsElement(arr, n))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
class GFG
{
static boolean containsElement( int [] arr, int n)
{
int xorArr = 0 ;
for ( int i = 0 ; i < n; ++i)
xorArr ^= arr[i];
for ( int i = 0 ; i < n; ++i)
{
int x = xorArr ^ arr[i];
if (arr[i] == x)
return true ;
}
return false ;
}
public static void main (String[] args)
{
int [] arr = { 8 , 2 , 4 , 15 , 1 };
int n = arr.length;
if (containsElement(arr, n))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def containsElement(arr, n):
xorArr = 0
for i in range (n):
xorArr ^ = arr[i]
for i in range (n):
x = xorArr ^ arr[i]
if (arr[i] = = x):
return True
return False
arr = [ 8 , 2 , 4 , 15 , 1 ]
n = len (arr)
if (containsElement(arr, n)):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
class GFG
{
static bool containsElement( int [] arr, int n)
{
int xorArr = 0;
for ( int i = 0; i < n; ++i)
xorArr ^= arr[i];
for ( int i = 0; i < n; ++i)
{
int x = xorArr ^ arr[i];
if (arr[i] == x)
return true ;
}
return false ;
}
public static void Main ()
{
int [] arr = { 8, 2, 4, 15, 1 };
int n = arr.Length;
if (containsElement(arr, n))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function containsElement(arr, n)
{
let xorArr = 0;
for (let i = 0; i < n; ++i)
xorArr ^= arr[i];
for (let i = 0; i < n; ++i) {
let x = xorArr ^ arr[i];
if (arr[i] == x)
return true ;
}
return false ;
}
let arr = [ 8, 2, 4, 15, 1 ];
let n = arr.length;
if (containsElement(arr, n))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time complexity: O(n) where n is size of input array
Auxiliary Space: O(1)
Last Updated :
05 Sep, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...