codejump
HardPro challengePythonJavaScriptTypeScript

Bits — Maximum XOR of Two Numbers

AlgorithmsBit ManipulationHash SetGreedy

solve(nums) — nums holds non-negative integers < 2^31. Return the maximum value of
nums[i] ^ nums[j] over all pairs with 0 <= i <= j < n (so a single-element array
gives 0). Comparing all pairs is O(n²); the target is O(31 · n).

Build the answer greedily, one bit at a time from the top. For bit b, keep only the
top bits of every number (the *prefixes*) and ask: can the answer have this bit set? That is
true when some two prefixes XOR to candidate = best | (1 << b) — checked in O(1) per
number with a Set, because p1 ^ p2 = candidate means p1 ^ candidate = p2.
A binary trie gives the same bound.

Examples

solve([3,10,5,25,2,8])                       → 28      // 5 ^ 25
solve([14,70,53,83,49,91,36,80,92,51,66,70]) → 127
solve([0])                                   → 0

Sample tests

Test #1All low bits reachable
Input: [[14,70,53,83,49,91,36,80,92,51,66,70]]
Output: 127
Test #2Single element
Input: [[0]]
Output: 0
Test #3Classic example
Input: [[3,10,5,25,2,8]]
Output: 28