Min Xor Pairs
1. You are given an array of distinct integers.Input Format
2. You have to print all pairs of integers in the array whose XOR value is minimum.
A number NOutput Format
arr1
arr2..
N numbers
Check the sample output and question video.Question Video
1 <= n <= 10^5Sample Input
-10^9 <= arr[i] <= 10^9
4Sample Output
2
0
5
7
0, 2
5, 7
-
Editorial
In this problem, we are provided with an array of integers and we need to print all integer pairs from this given array which have minimum XOR result.
A brute force approach would be to generate all pairs with two nested loops so we get the number of pairs equals NC2 and for every pair, we can calculate the XOR result and then return the minimum result. This approach has a time complexity of O(N2).
We can optimize the solution to O(NlogN) by using sorting.
Claim: If a <= b <= c then, either a ^ b < a ^ c or b ^ c < a ^ c
Proof:
a -> 1 1 0 1 0 ... => [same bits] [different bit] [non-significant bits]
b -> 1 1 0 1 0 ... => [same bits] [different bit] [non-significant bits]
c -> 1 1 0 1 1 ... => [same bits] [different bit] [non-significant bits]
a^b 0 0 0 0 1 ... => [0s...] [1] [redundant]
a^c 0 0 0 0 0 ... => [0s...] [0] [redundant]
Here a^b < a^c
a -> 1 1 0 1 0 ... => [same bits] [different bit] [non-significant bits]
b -> 1 1 0 1 1 ... => [same bits] [different bit] [non-significant bits]
c -> 1 1 0 1 1 ... => [same bits] [different bit] [non-significant bits]
b^c 0 0 0 0 1 ... => [0s...] [1] [redundant]
a^c 0 0 0 0 0 ... => [0s...] [0] [redundant]
Here b^c < a^c
Hence proved.
This claim implies that XOR of non-adjacent sorted numbers will always be less than XOR of the adjacent sorted number, i.e., if we have numbers [a, b, c] we already know that either pair (a, b) or pair (b, c) will be our result so pair (a, c) will be redundant. Expanding this idea to numbers [ a, b, c, d, e] then we only need to check XORs of (a, b), (b, c), (c, d), and (d, e).
Hence after sorting which takes O(NlogN) time we only need to traverse the array once to get our adjacent pairs XOR values.
Time Complexity: O(NlogN)
Sorting is involved which takes NlogN time.
Space Complexity: O(1)
The space complexity for the function is constant.
-
Asked in Companies
-
Related Topics