1542. Closest XOR Pair
Two coded tags are said to be close when the bitwise XOR of their values is small: the fewer high bits in which they differ, the closer they are. A warehouse holds a list of tags in the array nums and wants the closest pair.
Return the minimum value of nums[i] ^ nums[j] over all index pairs with i < j. Equal values may appear several times and then give a distance of 0. For example, for [9, 12, 5, 7] the pair 5 and 7 gives 2, and no other pair gives less.
Trying every pair is quadratic. Instead observe that after sorting the values, the pair with the smallest XOR is always two neighbours in sorted order, so a single scan over adjacent elements is enough. Aim for O(n log n) time and O(n) extra space for the sorted copy. All values and the answer fit in a 32-bit signed integer.
Example 1
- Input:
- nums = [9,12,5,7]
- Output:
- 2
- Explanation:
Among all pairs, 5 ^ 7 = 2 is the smallest XOR.
Example 2
- Input:
- nums = [1,2,3]
- Output:
- 1
- Explanation:
1 ^ 2 = 3, 1 ^ 3 = 2 and 2 ^ 3 = 1, so the minimum is 1.
Constraints
2 ≤ nums.length ≤ 105; 0 ≤ nums[i] ≤ 231 - 1
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,400 msC++ 600 msJava 1,200 msJavaScript 1,200 msTypeScript 1,200 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)