Maximum XOR of Two Numbers in an Array (LeetCode 421): Solution and Explanation

Medium
Array
Hash Table
Bit Manipulation
Trie

Given an array of non-negative integers, find the largest value of nums[i] XOR nums[j] over all pairs of indices. A number may be paired with itself, which gives 0.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Checking every pair is O(n²), which times out on large arrays. To do better, use the fact that XOR is decided bit by bit and that a higher bit is worth more than all lower bits combined. So build the answer greedily from the most significant bit: at each position, try to set the bit to 1 and keep it only if some pair can actually achieve it.

How do you check whether a 1 is achievable at the current bit? Look only at the top bits seen so far by masking every number with mask, which covers bits 31 down to i. The answer we hope for is candidate, our best answer so far with bit i also set. We need two prefixes a and b with a ^ b == candidate. XOR has the handy property that a ^ b == c is the same as a ^ c == b, so for each prefix a we just ask whether a ^ candidate is in the set of prefixes.

If such a pair exists, the bit is locked in; otherwise the answer keeps a 0 there. Because higher bits were decided first and every decision keeps the earlier bits fixed, the greedy choice is always optimal, and after 32 rounds the full maximum has been assembled.

Approach: Greedy bit construction with a prefix hash set

  1. Start with max_xor = 0 and mask = 0.
  2. Loop i from 31 down to 0, adding bit i to mask.
  3. Build the set prefixes of num & mask for every number.
  4. Form candidate = max_xor | (1 << i), the best answer so far with this bit turned on.
  5. If any prefix p has candidate ^ p also in the set, set max_xor = candidate.
  6. After all 32 bits, return max_xor.

Step-by-step example

nums = [3, 10, 5, 25, 2, 8]
  1. For bits 31 down to 5 every prefix is 0, so no candidate is reachable and max_xor stays 0.
  2. Bit 4: prefixes are {0, 16} (only 25 has bit 4). Candidate 16 works since 16 ^ 0 = 16 is present, so max_xor = 16.
  3. Bit 3: prefixes are {0, 8, 24}. Candidate 24 works because 24 ^ 0 = 24 is present, so max_xor = 24.
  4. Bit 2: prefixes are {0, 4, 8, 24}. Candidate 28 works because 28 ^ 4 = 24 is present, so max_xor = 28.
  5. Bits 1 and 0: candidates 30 and 29 find no matching pairs, so the answer stays 28, which is 5 ^ 25.

Code: Python, Java, C++

1class Solution:
2    def findMaximumXOR(self, nums: List[int]) -> int:
3        max_xor = 0
4        mask = 0
5
6        for i in range(31, -1, -1):
7            mask |= (1 << i)
8            prefixes = set()
9
10            for num in nums:
11                prefixes.add(num & mask)
12
13            candidate = max_xor | (1 << i)
14
15            for prefix in prefixes:
16                if (candidate ^ prefix) in prefixes:
17                    max_xor = candidate
18                    break
19
20        return max_xor

Time and space complexity

Time

O(n)

There are 32 rounds, and each builds a set of n prefixes and checks up to n of them, so the total is O(32 × n), which is linear.

Space

O(n)

The prefix set holds at most n values in each round.

Other approaches

Binary trie (time O(n), space O(n × 32))

Insert every number into a trie of its 32 bits, then for each number walk the trie choosing the opposite bit whenever possible to maximize XOR. Same linear bound with a larger constant for node allocation.

Brute force over pairs (time O(n²), space O(1))

XOR every pair and keep the maximum. Simple and correct, but quadratic.

Common mistakes

  • Rebuilding mask wrong, for example setting it to 1 << i alone instead of accumulating with |=. The prefixes must include all higher bits.
  • Testing candidate directly against the set instead of candidate ^ prefix. The question is whether two prefixes combine to the candidate, not whether the candidate itself is a prefix.
  • Breaking out of the outer loop after a bit fails. A 0 at one bit does not stop later bits from being 1.
  • Starting from a lower bit, such as the bit length of the smallest number. Start from the highest bit any number could have.

Frequently asked questions

Why does the greedy bit-by-bit method work?

A 1 in a higher bit is worth more than all lower bits combined, so it is always right to secure the highest bit first. Each later decision keeps the earlier bits fixed, so the result is the true maximum.

Why check if candidate ^ prefix is in the set?

If a ^ b == candidate, then a ^ candidate == b. So for each prefix a you only need to look up a ^ candidate in the set, which is a constant-time check.

Is the trie solution better?

Both are linear. The trie is easier to visualize and extends naturally to queries, while the hash set version is shorter and uses less memory.

What is the time complexity of maximum XOR of two numbers?

O(32 × n), which is O(n), because each of the 32 rounds processes every number a constant number of times.