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 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
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 .
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.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.