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 of Two Numbers in an Array INPUT Integer Array nums[] 3 10 5 25 2 8 Binary Form: 3 = 00011 10 = 01010 5 = 00101 25 = 11001 2 = 00010 8 = 01000 XOR: Returns 1 when bits differ, 0 when same 1 XOR 0 = 1, 1 XOR 1 = 0 ALGORITHM STEPS 1 Build Trie Insert all nums as binary R 0 1 2 Query Each Number Find max XOR partner 3 Greedy Choice Pick opposite bit if exists 4 Track Maximum Update max XOR result Best Pair Found: 5 = 00101 25 = 11001 XOR = 11100 = 28 FINAL RESULT Maximum XOR Value 28 Calculation: nums[2] = 5 (00101) nums[3] = 25 (11001) 5 XOR 25 = 28 (11100) Verification: All pairs checked OK - 28 is maximum Key Insight: Using a Trie (prefix tree) allows O(n * log(max)) time complexity instead of O(n^2) brute force. For each number, greedily choose opposite bits from MSB to LSB to maximize XOR result. The Trie stores binary representations, enabling efficient search for the best XOR partner. TutorialsPoint - Maximum XOR of Two Numbers in an Array | Optimal Solution (Trie-based)
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