Maximum XOR of Two Numbers in an Array

Medium

Topics
ArrayBit ManipulationTrieHash Table

Given an integer array nums, return the maximum result of nums[i] XOR nums[j] over all pairs 0 <= i <= j < n.

Example 1

30101522532485
Input:  nums = [3,10,5,25,2,8]
Output: 28
Explanation: 5 XOR 25 = 28 is the largest pairwise XOR.

Example 2

14070153283349491536680792851966107011
Input:  nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127

Example 3

00
Input:  nums = [0]
Output: 0

Constraints

  • 1 <= nums.length <= 2 * 10^5
  • 0 <= nums[i] < 2^31
Editorial — intuition, approach, complexity and pitfalls

Intuition

XOR is decided bit by bit from the top, and a higher bit outweighs every lower bit combined. So build the answer greedily: assume you can set the current bit, then ask whether any pair actually achieves the prefix you have assumed. The check is one XOR identity - if a ^ b == target then a ^ target == b - so a hash set of prefixes answers it in O(n) per bit.

Approach

  1. Start with answer = 0 and walk bits from 30 down to 0.
  2. Let candidate = answer | (1 << bit) - the prefix you hope to achieve.
  3. Collect the high prefixes of every number: prefixes = {num >> bit ... }, masked to the bits considered so far.
  4. If some prefix p has p ^ candidate also in the set, the candidate is reachable - set answer = candidate. Otherwise leave the bit at zero and move on.
  5. The alternative is a binary trie: insert every number as a 32-bit path, then for each number walk greedily toward the opposite bit at each level.
class Solution:
    def findMaximumXOR(self, nums):
        answer = 0
        for bit in range(30, -1, -1):
            answer <<= 1
            prefixes = {num >> bit for num in nums}
            candidate = answer | 1
            if any(candidate ^ p in prefixes for p in prefixes):
                answer = candidate
        return answer

Dry Run

nums [3, 10, 5, 25, 2, 8], which in 5 bits are
  3 = 00011   10 = 01010   5 = 00101   25 = 11001   2 = 00010   8 = 01000
Build the answer one bit at a time from the TOP, each round asking "can I also set
this bit?" and keeping the prefixes masked to the same width.
  bit 4   mask 10000   prefixes {0, 16}                 try 16   yes   best 16
  bit 3   mask 11000   prefixes {0, 8, 24}              try 24   yes   best 24
  bit 2   mask 11100   prefixes {0, 4, 8, 24}           try 28   yes   best 28
  bit 1   mask 11110   prefixes {2, 4, 8, 10, 24}       try 30   no    best 28
  bit 0   mask 11111   prefixes {2, 3, 5, 8, 10, 25}    try 29   no    best 28
answer 28    --  5 ^ 25
The test for each candidate is the XOR identity: if a ^ b == candidate then
a == candidate ^ b, so a single set membership check over the prefixes answers
"does some pair reach this?" in O(n) rather than O(n^2).
High bit first is not a preference, it is the only order that works. A high bit is
worth more than every lower bit combined, so it must be claimed whenever possible
and never traded. Build from the low bit up and this input returns 15 instead
of 28.
The mask ACCUMULATES -- `mask |= 1 << bit`, not `mask = 1 << bit`. Prefixes must
all be the same width, or a 5-bit prefix gets compared against a 1-bit one and the
search finds pairs that do not exist: with the mask merely set rather than
accumulated, the answer comes back 16.
In Java and JavaScript, shifting 31 bits with << produces a negative int, so cap
the loop at bit 30 for the stated constraints.

Complexity

  • Time — O(32n) — one linear scan per bit, so linear in practice.
  • Space — O(n) for the prefix set, or O(32n) nodes for the trie variant.

Common Pitfalls

  • Greedy works only from the high bit down. Building the answer from the low bit gives nonsense, because a low bit can never compensate for a lost high bit.
  • Mask the prefixes to the same width every iteration. Comparing a 5-bit prefix against a 6-bit one finds pairs that do not exist.
  • The pair may be i == j by the problem statement, but that yields 0 and never beats a real pair unless n is 1.
  • Watch the sign bit in Java and JavaScript. Shifting 31 bits with << produces a negative int, so cap the loop at bit 30 for the stated constraints.

Full Solution — all languages

class Solution:
    def findMaximumXOR(self, nums):
        best = 0
        mask = 0
        for bit in range(31, -1, -1):
            mask |= 1 << bit
            prefixes = {v & mask for v in nums}
            candidate = best | (1 << bit)
            if any(candidate ^ p in prefixes for p in prefixes):
                best = candidate
        return best
SensAI
Beta
Tap the mic to stop voice mode