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
XOR Maximization: The Binary DanceROOT010101Seeking Opposite PathThe XOR Strategy1. For number 5 (101), we want to find a number that differs in as many high-order bits as possible2. Traverse trie always choosing opposite bit when available (0→1, 1→0)3. This maximizes each bit position in the final XOR result
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

n
2n
Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track the maximum XOR value

n
2n
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?
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28 Apple 22
42.5K Views
Medium-High Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen