Maximum XOR of Two Numbers in an Array - Problem

Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.

The XOR operation compares bits and returns 1 when bits differ and 0 when they're the same.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,10,5,25,2,8]
Output: 28
💡 Note: The maximum XOR is achieved by 5 XOR 25 = 28. In binary: 00101 XOR 11001 = 11100 = 28
Example 2 — Simple Pair
$ Input: nums = [14,70,53,83,49,91,36,80,92,51,66,70]
Output: 127
💡 Note: The maximum XOR is 127. We need to find the pair that gives maximum difference in bits
Example 3 — Edge Case
$ Input: nums = [8,10,2]
Output: 10
💡 Note: Maximum XOR is between 8 XOR 2 = 10. In binary: 1000 XOR 0010 = 1010 = 10

Constraints

  • 1 ≤ nums.length ≤ 2 * 104
  • 0 ≤ nums[i] ≤ 231 - 1

Visualization

Tap to expand
Maximum XOR Problem: Find Best Pair31052528Best pair: 5 and 255 in binary: 0010125 in binary: 11001XOR result: 11100XOR Operation:00101 (5)11001 (25)-----11100 (28)Result: 28
Understanding the Visualization
1
Input Array
Array of integers [3,10,5,25,2,8]
2
XOR Operation
Find pair with maximum XOR value
3
Output
Return maximum XOR result: 28
Key Takeaway
🎯 Key Insight: XOR maximizes when bits differ most - build result bit by bit for efficiency
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 25
78.0K Views
Medium Frequency
~25 min Avg. Time
2.1K 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