Maximum XOR with an Element from Array
Master this topic with zero to advance depth.
Maximum XOR with an Element from Array
Given an integer array nums, return the maximum value of nums[j] XOR xi where nums[j] <= mi. If all numbers in nums are larger than mi, the answer is -1.
Visual Representation
Nums: [0, 1, 2, 3, 4]
Query: [3, 1] (x=3, m=1)
Valid nums <= 1: [0, 1]
XOR results: 3^0=3, 3^1=2
Max: 3
Optimal approach:
1. Sort nums.
2. Sort queries by m.
3. Insert nums into Trie as long as nums[j] <= m.
4. Query Trie for max XOR.Examples
Level I: Brute Force
Intuition
For each query [xi, mi], iterate through every number in the nums array. If nums[j] <= mi, calculate nums[j] XOR xi and update the maximum. Simple O(N*Q) solution.
Level III: Offline Queries + Binary Trie
Intuition
Since we need to check , we can sort both and (by ). By processing queries offline in non-decreasing order of , we only insert numbers into the Trie when they become 'valid' for the current . This transforms the conditional maximum problem into a standard Maximum XOR problem on a growing Trie.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.