Remove one element to get maximum XOR
Last Updated :
03 Mar, 2022
Given an array arr[] of N elements, the task is to remove one element from the array such that the XOR value of the array is maximized. Print the maximized value.
Examples:
Input: arr[] = {1, 1, 3}
Output: 2
All possible ways of deleting one element and their corresponding XOR values will be:
a) Remove 1 -> (1 XOR 3) = 2
b) Remove 1 -> (1 XOR 3) = 2
c) Remove 3 -> (1 XOR 1) = 0
Thus, the final answer is 2.
Input: arr[] = {3, 3, 3}
Output: 0
Naive approach: One way will be to remove each element one by one and then finding the XOR of the remaining elements. The time complexity of this approach will be O(N2).
Efficient approach:
- Find XOR of all the elements of the array. Let’s call this value X.
- For each element arr[i], perform Y = (X XOR arr[i]) and update the final answer as ans = max(Y, ans).
The above method works because if (A XOR B) = C then (C XOR B) = A. To find XOR(arr[0…i-1]) ^ XOR(arr[i+1…N-1]), all we have to perform is XOR(arr) ^ arr[i] where XOR(arr) is the XOR of all the elements of the array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxXOR( int * arr, int n)
{
int xorArr = 0;
for ( int i = 0; i < n; i++)
xorArr ^= arr[i];
int ans = 0;
for ( int i = 0; i < n; i++)
ans = max(ans, (xorArr ^ arr[i]));
return ans;
}
int main()
{
int arr[] = { 1, 1, 3 };
int n = sizeof (arr) / sizeof ( int );
cout << maxXOR(arr, n);
return 0;
}
|
Java
class GFG
{
static int maxXOR( int arr[], int n)
{
int xorArr = 0 ;
for ( int i = 0 ; i < n; i++)
xorArr ^= arr[i];
int ans = 0 ;
for ( int i = 0 ; i < n; i++)
ans = Math.max(ans, (xorArr ^ arr[i]));
return ans;
}
public static void main (String[] args)
{
int arr[] = { 1 , 1 , 3 };
int n = arr.length;
System.out.println(maxXOR(arr, n));
}
}
|
Python3
def maxXOR(arr, n):
xorArr = 0
for i in range (n):
xorArr ^ = arr[i]
ans = 0
for i in range (n):
ans = max (ans, (xorArr ^ arr[i]))
return ans
arr = [ 1 , 1 , 3 ]
n = len (arr)
print (maxXOR(arr, n))
|
C#
using System;
class GFG
{
static int maxXOR( int []arr, int n)
{
int xorArr = 0;
for ( int i = 0; i < n; i++)
xorArr ^= arr[i];
int ans = 0;
for ( int i = 0; i < n; i++)
ans = Math.Max(ans, (xorArr ^ arr[i]));
return ans;
}
public static void Main(String[] args)
{
int []arr = { 1, 1, 3 };
int n = arr.Length;
Console.WriteLine(maxXOR(arr, n));
}
}
|
Javascript
<script>
function maxXOR(arr, n)
{
let xorArr = 0;
for (let i = 0; i < n; i++)
xorArr ^= arr[i];
let ans = 0;
for (let i = 0; i < n; i++)
ans = Math.max(ans, (xorArr ^ arr[i]));
return ans;
}
let arr = [ 1, 1, 3 ];
let n = arr.length;
document.write(maxXOR(arr, n));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...