Posts Min XOR value (InterviewBit)
Post
Cancel

Min XOR value (InterviewBit)

PROBLEM DESCRIPTION

Given an integer array A of N integers, find the pair of integers in the array which have minimum XOR value. Report the minimum XOR value.

SOLUTION

By sorting the array, we ensure that adjacent elements are closest to each other in value. This is crucial because XORing two numbers with similar values will result in a smaller XOR value compared to XORing two numbers with larger differences. Sorting the array enables us to efficiently compare adjacent elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {

    public int findMinXor(int[] A) {

        Arrays.sort(A);

        int n = A.length;
        int ans = Integer.MAX_VALUE;

        for(int i=0; i<n-1; i++){
            ans = Math.min(ans, (A[i]^A[i+1]));
        }

        return ans;

    }

}
This post is licensed under CC BY 4.0 by the author.