Maximum XOR of Two Numbers in an Array
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Bit Manipulation.
Maximum XOR of Two Numbers in an Array
Given an integer array
nums, return the maximum result of nums[i] XOR nums[j], where .Examples
Input: nums = [3,10,5,25,2,8]
Output: 28
Approach 1
Level I: Brute Force (All Pairs)
Intuition
Check every possible pair of numbers and calculate their XOR sum. Track the maximum value found.
Thought Process
- Initialize
maxResult = 0. - Nested loop through
nums. maxResult = max(maxResult, nums[i] ^ nums[j]).- Return
maxResult.
Pattern: Double Iteration
⏱ O(N^2) - Where $N$ is the number of elements in the array.💾 O(1) - Constant space.
Approach 2
Level II: Greedy Comparison with Hash Set
Intuition
We can build the maximum XOR bit by bit. For each bit position (from MSB to LSB), we check if there exists a pair of numbers whose -th bits could potentially form a better maximum XOR than what we have found so far.
⏱ $O(N \cdot 32)$💾 $O(N)$
Approach 3
Level III: Optimal (Binary Trie)
Intuition
To maximize XOR, for each number , we want to find another number such that they have different bits at the highest possible positions. A Trie (Prefix Tree) storing binary representations allows us to greedily find the bitwise opposite at each step.
Thought Process
- Insert all numbers into a Trie of depth 31.
- For each number :
- Start at the Trie root.
- For each bit of (from MSB to LSB):
- If we want bit and it exists in the Trie, move there and add to our current XOR.
- Else, move to the child with bit .
- Track the best XOR found for any .
Pattern: Bitwise Greedy with Trie
⏱ O(N \cdot 32) - Linear pass to build Trie and another to query.💾 O(N \cdot 32) - Store numbers bit-by-bit in Trie nodes.
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.