Maximum XOR of Two Numbers in an Array - Problem
Given an integer array nums, your task is to find the maximum XOR (exclusive OR) value that can be obtained by combining any two numbers from the array.
The XOR operation compares bits of two numbers and returns 1 when bits are different, 0 when they're the same. For example: 3 XOR 5 = 011 XOR 101 = 110 = 6.
Goal: Return the maximum result of nums[i] XOR nums[j] where 0 ≤ i ≤ j < n.
Note: You can use the same element twice (when i = j) or different elements.
Input & Output
example_1.py — Basic case
$
Input:
nums = [3, 10, 5, 25, 2, 8]
›
Output:
28
💡 Note:
The maximum result is 5 XOR 25 = 28. In binary: 101 XOR 11001 = 11100 = 28
example_2.py — Small array
$
Input:
nums = [14, 70, 53, 83, 49, 91, 36, 80, 92, 51, 66, 70]
›
Output:
127
💡 Note:
The maximum XOR is achieved by combining 36 (100100) and 91 (1011011) = 127
example_3.py — Edge case
$
Input:
nums = [8, 10, 2]
›
Output:
10
💡 Note:
Possible XORs: 8^10=2, 8^2=10, 10^2=8. Maximum is 10
Visualization
Tap to expand
Understanding the Visualization
1
Build Binary Tree
Create a Trie storing all numbers as binary paths from most significant bit
2
Seek Opposites
For each number, traverse the tree always trying to go the opposite direction
3
Maximize Each Bit
When possible, choose the path that makes the current bit position 1 in the XOR result
4
Track Maximum
Keep track of the highest XOR value found across all number combinations
Key Takeaway
🎯 Key Insight: XOR is maximized when bits differ in the most significant positions. The Trie allows us to greedily choose the best partner for each number by always seeking opposite bits.
Time & Space Complexity
Time Complexity
O(n²)
We check all possible pairs of numbers, which gives us n×(n-1)/2 ≈ n² comparisons
⚠ Quadratic Growth
Space Complexity
O(1)
Only using a few variables to track the maximum XOR value
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 2 × 104
- 0 ≤ nums[i] ≤ 231 - 1
- Follow up: Can you solve it in O(n log(max_value)) time?
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code