Maximum XOR of Two Numbers in an Array
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
Maximum XOR of Two Numbers in an Array
Given an integer array
nums, return the maximum result of nums[i] XOR nums[j], where 0 <= i <= j < n.Visual Representation
Nums: [3, 10, 5, 25, 2, 8]
Max XOR: 5 XOR 25 = 28
Binary Trie approach:
1. Insert all numbers as 32-bit binary strings into a Trie.
2. For each number X, find a path that maximizes XOR.
3. To maximize XOR, at each bit, try to go to the opposite bit (if curr is 0, try 1).
If opposite exists, result |= (1 << bit).Examples
Input: nums = [3,10,5,25,2,8]
Output: 28
Approach 1
Level I: Brute Force
Intuition
Check every pair of numbers in the array and calculate their XOR. Keep track of the maximum XOR found. Simple but .
⏱ O(N^2)💾 O(1)
Approach 2
Level III: Binary Trie
Intuition
Represent each number as a 31-bit or 32-bit binary string. Insert all numbers into a Trie where each node has at most two children (0 and 1). For each number , we want to find a number such that is maximized. At each bit of , if the -th bit is , we prioritize moving to a child representing in the Trie. This greedy choice at each bit ensures the maximum possible XOR value.
⏱ O(N * 31) = O(N).💾 O(N * 31).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.