Maximum XOR pair
Standard · Write code · about 20 min
Given nums, return the largest value of nums[i] XOR nums[j] over all pairs with i ≤ j. A number paired with itself gives 0. For an empty array, return 0.
Store the numbers as 30-bit paths in a binary trie. For each number, walk the trie and prefer the opposite bit at every level.
Example 1
Input:
[[3,10,5,25,2,8]]
Output:
28
5 XOR 25 = 28 is the best pair.
Example 2
Input:
[[8,8,8]]
Output:
0
Equal numbers XOR to 0.
Constraints
- 0 ≤ nums.length ≤ 2,000
- 0 ≤ nums[i] < 2³⁰
Learn the idea first: Trie applications: autocomplete, word search, XOR maximum, a visual lesson.
More Trie applications: autocomplete, word search, XOR maximum problems
- Replace words Warm-up
- Autocomplete top-3 Standard
- Trace the XOR walk Standard
- Word search on a board Challenge