← DiffPush

Maximum XOR of Two Numbers in an Array

Standard Bar Tries · Problems O(n * 32) · O(n * 32)

The Cipher Mask Championship

A red-team exercise stores device keys as 32-bit words. The prize goes to the pair of devices whose keys disagree in the most significant bit positions — the pair whose XOR is largest. The analyzer inserts every key into a bit-wise trie, then walks each key against the trie, always chasing the branch that flips its current bit.

Input: An array nums of n non-negative integers.

Output: Return the maximum value of nums[i] XOR nums[j] over all pairs (i and j may be equal only in the trivial zero case; the meaningful answer uses distinct positions).

Constraints

Examples

Example 1

Input: {"nums":[3,10,5,25,2,8]}
Output: 28
5 XOR 25 = 28, the strongest disagreement pattern in the set.

Example 2

Input: {"nums":[14,70,53,83,49,91,36,80,92,51,66,70]}
Output: 127
91 XOR 36 = 127 — the seven low bits all disagree between the two keys.

Solve this in your browser →

Also on LeetCode ↗