Maximum XOR of Two Numbers in an Array (LeetCode 421): Solution and Explanation
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.
Watch it run step by step
Try your own input and write the code →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
- Start with
max_xor = 0andmask = 0. - Loop
ifrom 31 down to 0, adding bititomask. - Build the set
prefixesofnum & maskfor every number. - Form
candidate = max_xor | (1 << i), the best answer so far with this bit turned on. - If any prefix
phascandidate ^ palso in the set, setmax_xor = candidate. - After all 32 bits, return
max_xor.
Step-by-step example
nums = [3, 10, 5, 25, 2, 8]
- For bits 31 down to 5 every prefix is 0, so no candidate is reachable and
max_xorstays 0. - Bit 4: prefixes are
{0, 16}(only 25 has bit 4). Candidate 16 works since16 ^ 0 = 16is present, somax_xor = 16. - Bit 3: prefixes are
{0, 8, 24}. Candidate 24 works because24 ^ 0 = 24is present, somax_xor = 24. - Bit 2: prefixes are
{0, 4, 8, 24}. Candidate 28 works because28 ^ 4 = 24is present, somax_xor = 28. - 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_xor1class Solution {
2 public int findMaximumXOR(int[] nums) {
3 int maxXor = 0;
4 int mask = 0;
5
6 for (int i = 31; i >= 0; i--) {
7 mask |= (1 << i);
8 Set<Integer> prefixes = new HashSet<>();
9
10 for (int num : nums) {
11 prefixes.add(num & mask);
12 }
13
14 int candidate = maxXor | (1 << i);
15
16 for (int prefix : prefixes) {
17 if (prefixes.contains(candidate ^ prefix)) {
18 maxXor = candidate;
19 break;
20 }
21 }
22 }
23
24 return maxXor;
25 }
26}1class Solution {
2public:
3 int findMaximumXOR(vector<int>& nums) {
4 int maxXor = 0;
5 int mask = 0;
6
7 for (int i = 31; i >= 0; i--) {
8 mask |= (1 << i);
9 unordered_set<int> prefixes;
10
11 for (int num : nums) {
12 prefixes.insert(num & mask);
13 }
14
15 int candidate = maxXor | (1 << i);
16
17 for (int prefix : prefixes) {
18 if (prefixes.count(candidate ^ prefix)) {
19 maxXor = candidate;
20 break;
21 }
22 }
23 }
24
25 return maxXor;
26 }
27};Time and space complexity
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.
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
maskwrong, for example setting it to1 << ialone instead of accumulating with|=. The prefixes must include all higher bits. - Testing
candidatedirectly against the set instead ofcandidate ^ 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.