Maximum XOR of Two Numbers in an Array
Difficulty: Medium · Pattern: Tries · LeetCode #421
Given an integer array nums (0 ≤ nums[i] < 2³¹), return the maximum value of nums[i] XOR nums[j] with 0 ≤ i ≤ j < n.
Examples
text
[3,10,5,25,2,8] → 28 (5 XOR 25 = 00101 ^ 11001 = 11100)
[14,70,53,83,49,91,36,80,92,51,66,70] → 127Hints
- XOR is maximized by making the highest bits 1 first. A higher bit is worth more than all lower bits combined.
- Store every number's 31 bits in a binary trie (each node has children 0 and 1). For a query
x, at each bit try to go toward the opposite bit.
Approach
Bitwise trie, greedy from the most significant bit:
text
for each x in nums:
insert x's bits (bit 30 → bit 0) into the trie
walk the trie for x: at bit b, want = 1 - bit(x, b)
if the child 'want' exists: go there, result |= (1 << b)
else: go to the other child
best = max(best, result)Greedy is correct because setting bit b beats any combination of bits < b (2^b > 2^b − 1). Inserting before querying keeps the trie non-empty, and i == j gives XOR 0, which is fine.
O(31·n). The other well-known solution builds the answer bit by bit with a hash set of prefixes (ans | 1 is achievable if p ^ candidate is in the prefix set).
Complexity
Time: O(31·n). Space: O(31·n) trie nodes.
Python solution
def findMaximumXOR(nums):
root, best = {}, 0
for x in nums:
node = root
for b in range(30, -1, -1):
node = node.setdefault((x >> b) & 1, {})
node, cur = root, 0
for b in range(30, -1, -1):
want = 1 - ((x >> b) & 1)
if want in node:
cur |= 1 << b
node = node[want]
else:
node = node[1 - want]
best = max(best, cur)
return bestJavaScript solution
function findMaximumXOR(nums) {
const root = [null, null];
let best = 0;
for (const x of nums) {
let node = root;
for (let b = 30; b >= 0; b--) { const bit = (x >> b) & 1; node = node[bit] ??= [null, null]; }
node = root;
let cur = 0;
for (let b = 30; b >= 0; b--) {
const want = 1 - ((x >> b) & 1);
if (node[want]) { cur |= 1 << b; node = node[want]; } else node = node[1 - want];
}
best = Math.max(best, cur);
}
return best;
}