Maximum XOR of Two Numbers in an Array Problem
Description
LeetCode Problem 421. Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n.
Example:
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
Solution
Approach: Greedy Bit by Bit with Prefix Sets
Comparing every pair takes O(n2) time. Instead, build the answer one bit at a time, from the highest bit down. A higher bit is worth more than all lower bits together, so whenever we can make the current bit 1, we should.
The numbers are below 231, so start at bit 30. Suppose answer already holds the best value of the bits above the current one. For the current bit:
- Shift
answerleft and trycandidate = answer | 1. - Collect
prefixes: every number shifted right bybit, so only its bits from the top down tobitremain. - We need two prefixes
aandbwitha ^ b == candidate. Sincea ^ b == candidatemeansb == a ^ candidate, this is a set lookup: check whetherp ^ candidateis inprefixesfor somep. - If such a pair exists, keep
candidate; otherwise the bit stays 0.
Why the greedy choice is safe: the top bits of the maximum XOR form the largest prefix that any pair can reach, and a pair that reaches candidate also reaches the prefix chosen before it, so each step extends the best prefix by one bit. The pair that reaches it may change from one bit to the next; only the value matters.
For [3, 10, 5, 25, 2, 8], the high bits pick 25 (11001) and 5 (00101): 25 ^ 5 = 28 (11100).
Complexity: O(n · B) time and O(n) space, where n is the length of nums and B = 31 is the number of bits.
class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
answer = 0 # the best XOR of the top bits decided so far
for bit in range(30, -1, -1): # nums[i] < 2^31, so bit 30 is the highest one that can be set
answer <<= 1
candidate = answer | 1 # try to make this bit 1 as well
prefixes = {x >> bit for x in nums} # every number's bits from the top down to this bit
# Two prefixes a, b with a ^ b == candidate exist exactly when a ^ candidate is also a prefix.
if any(p ^ candidate in prefixes for p in prefixes):
answer = candidate
return answer
Now write it from memory
Close the write-up and solve it yourself against the tests.