Given an integer array A of N integers, find the pair of integers in the array which have minimum XOR value Here is the Brute Force solution where we find every pair possible and compute XOR and find the minimum of every pair :
int minXOR(int arr[], int n)
{
int min_xor = INT_MAX; // Initialize result
// Generate all pair of given array
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
// update minimum xor value if required
min_xor = min(min_xor, arr[i] ^ arr[j]);
return min_xor;
}
Here is the code with O(n*logn) complexity :
int Solution::findMinXor(vector<int> &A) {
sort(A.begin(),A.end());
int min=INT_MAX;
int val;
for(int i=0;i<A.size();i++)
{
val=A[i]^A[i+1];
if(val<min)
min=val;
}
return min;
}
My doubt is, how does sorting help in finding the minimum xor valued pairs ? In this solution we are finding the xor of only the consecutive sorted elements. Will we not be missing out other potential minimum xor value pairs that are not consecutive ? I'm still learning bit manipulations, so forgive me if this doubt seems too stupid.