Maximum XOR of Two Numbers in an Array
Maximum XOR of Two Numbers in an Array
Problem Statement
Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 is less than or equal to i, which is less than or equal to j, which is less than n.
Example
Input: nums = [3,10,5,25,2,8]
Output: 28
Explanation: The maximum result is 5 XOR 25 = 28.
Solution (Trie)
To find the maximum XOR value for each number, we can use a Trie (prefix tree) to store the binary representations of the numbers seen so far. For each number, we traverse the Trie to find a previously inserted number that will maximize the XOR result.
To maximize the XOR, we greedily try to find a path in the Trie that has the opposite bit at each position. If the current bit of our number is 1, we want to find a 0 in the Trie, and vice versa.
Algorithm Steps
- Create a Trie data structure.
- Insert the binary representation of each number in the input array into the Trie.
- For each number in the array, traverse the Trie to find the number that would give the maximum XOR.
- Start from the most significant bit. If the current bit is 1, try to go to the 0 child in the Trie. If it's 0, try to go to the 1 child.
- If the desired opposite path exists, take it and add a 1 to the current maximum for that number. If not, take the existing path.
- Keep track of the overall maximum XOR value found across all numbers.
Input `nums`
Trie Structure
Current Number: N/A
Current Max XOR: N/A
Overall Max XOR: 0