Maximum XOR of Two Numbers in an Array
Master this topic with zero to advance depth.
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
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
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.
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
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.