Minimum XOR of OR and AND of any pair in the Array
Last Updated :
05 May, 2021
Given an array arr[] of N positive integers the task is to find the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array.
Examples:
Input: arr[] = {1, 2, 3, 4, 5}
Output: 1
Explanation:
For element 2 & 3:
The value of the expression (2&3) xor (2|3) is 1, which is the minimum from all the pairs in the given array.
Input : arr[] = {3, 6, 8, 4, 5}
Output : 1
Explanation:
For element 4 & 5:
The value of the expression (4&5) xor (4|5) is 1, which is the minimum from all the pairs in the given array.
Approach: For any pairs of elements say X and Y, the value of the expression (X&Y) xor (X|Y) can be written as:
=> (X.Y)^(X+Y)
=> (X.Y)(X+Y)’ + (X.Y)'(X+Y)
=> (X.Y)(X’.Y’) + (X’+Y’)(X+Y)
=> X.X’.Y.Y’ + X’.X + X’.Y + Y’.X + Y’.Y
=> 0 + 0 + X’.Y + Y’.X + 0
=> X^Y
From the above calculations, for any pairs (X, Y) in the given array, the expression (X&Y) xor (X|Y) is reduced to X xor Y. Therefore, the minimum value of Bitwise XOR of Bitwise OR and AND of any pair in the given array is given XOR of minimum value pair which can be calculated using the approach discussed in this article.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int maxAndXor( int arr[], int n)
{
int ans = INT_MAX;
sort(arr, arr + n);
for ( int i = 0; i < n - 1; i++) {
ans = min(ans, arr[i] ^ arr[i + 1]);
}
return ans;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << maxAndXor(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.util.Arrays;
class GFG {
static int maxAndXor( int arr[], int n)
{
int ans = Integer.MAX_VALUE;
Arrays.sort(arr);
for ( int i = 0 ; i < n - 1 ; i++) {
ans = Math.min(ans, arr[i] ^ arr[i + 1 ]);
}
return ans;
}
public static void main(String[] args)
{
int arr[] = new int [] { 1 , 2 , 3 , 4 , 5 };
int N = arr.length;
System.out.println(maxAndXor(arr, N));
}
}
|
Python3
def maxAndXor(arr, n):
ans = float ( 'inf' )
arr.sort()
for i in range (n - 1 ):
ans = min (ans, arr[i] ^ arr[i + 1 ])
return ans
if __name__ = = '__main__' :
arr = [ 1 , 2 , 3 , 4 , 5 ]
N = len (arr)
print (maxAndXor(arr, N))
|
C#
using System;
class GFG {
static int maxAndXor( int [] arr, int n)
{
int ans = 9999999;
Array.Sort(arr);
for ( int i = 0; i < n - 1; i++) {
ans = Math.Min(ans, arr[i] ^ arr[i + 1]);
}
return ans;
}
public static void Main()
{
int [] arr = new int [] { 1, 2, 3, 4, 5 };
int N = arr.Length;
Console.Write(maxAndXor(arr, N));
}
}
|
Javascript
<script>
function maxAndXor(arr, n)
{
let ans = Number.MAX_VALUE;
arr.sort();
for (let i = 0; i < n - 1; i++) {
ans = Math.min(ans, arr[i] ^ arr[i + 1]);
}
return ans;
}
let arr = [ 1, 2, 3, 4, 5 ];
let N = arr.length;
document.write(maxAndXor(arr, N));
</script>
|
Time Complexity: O(N*log N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...