Maximum XOR with an Element from Array
Expert Answer & Key Takeaways
A complete guide to understanding and implementing Trie.
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
Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
Output: [3,3,7]
Approach 1
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.⏱ O(N * Q)💾 O(1)
Approach 2
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.
⏱ O(N log N + Q log Q + (N+Q) * 31).💾 O(N * 31).
Course4All Technical Board
Verified ExpertSenior Software Engineers & Algorithmic Experts
Our DSA content is authored and reviewed by engineers from top tech firms to ensure optimal time and space complexity analysis.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.