XOR is minimized for adjacent sorted elements
Find the minimum xor of a pair of numbers from the given array.
Suppose the minimum xor is between a pair of numbers
We claim that there is no
in the array such that .
Assume that there does exist
- If it is
, we could do and the resulting number will have the bit at position as . - If it is
, we could do and the resulting number will have the bit at position as .
Hence, it’s always possible to improve the answer by either deleting
To compute minimum xor of all possible pairs, sort the array. The minimum xor pair will now be adjacent to each other.
Let’s look at an example.
If there is a
- Suppose
. Then, if we do , the new xor would be . - Suppose
, then doing yields . In either case, we were able to turn off the bit. Sure, some lower order bits were turned on, but remember the expression
This means that the power of all the smaller bits combined is not enough to reach the level of
You can find the code here
Depending upon your familiarity with bitwise operations, some of the following things might not be obvious to you.
- Why do we claim that the higher order bits of
(the ones after index ) are identical to those of . In fact, why are the bits of and after index identical?
The bits of index
Now, why should the bits of
Recall the expression,
Break down
- Why are we only focusing on turning off the
bit? What if we accidentally turn on a more significant bit of the xor in the process, thereby increasing the xor?
As proved above, the bits of
- The minimum xor pair will not have any gaps in between them. However, this doesn’t mean that the xor would increase if the absolute difference between numbers increases. For example,
while and
Binary Spiders can be solved in
I will add my solution and explanation for
The editorial of Binary Spiders mentions this fact. Although I was able to prove it after reading the editorial using the same idea discussed in this blog, I did refer to this comment by Perpetually_Purple to validate that my idea was indeed correct.