Maximum XOR With an Element From Array - Problem

You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [xi, mi].

The answer to the ith query is the maximum bitwise XOR value of xi and any element of nums that does not exceed mi. In other words, the answer is max(nums[j] XOR xi) for all j such that nums[j] <= mi. If all elements in nums are larger than mi, then the answer is -1.

Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the ith query.

Input & Output

Example 1 — Basic Queries
$ Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
Output: [3,3,7]
💡 Note: Query [3,1]: Valid elements ≤1 are {0,1}. Max XOR: max(0⊕3, 1⊕3) = max(3,2) = 3. Query [1,3]: Valid elements ≤3 are {0,1,2,3}. Max XOR: max(0⊕1, 1⊕1, 2⊕1, 3⊕1) = max(1,0,3,2) = 3. Query [5,6]: All elements ≤6, Max XOR: max(0⊕5, 1⊕5, 2⊕5, 3⊕5, 4⊕5) = max(5,4,7,6,1) = 7.
Example 2 — No Valid Elements
$ Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]
Output: [15,-1,4]
💡 Note: Query [12,4]: Valid elements ≤4 are {2,4,3}. Max XOR: max(2⊕12, 4⊕12, 3⊕12) = max(14,8,15) = 15. Query [8,1]: No elements ≤1, return -1. Query [6,3]: Valid elements ≤3 are {2,3}. Max XOR: max(2⊕6, 3⊕6) = max(4,5) = 5.
Example 3 — Edge Case
$ Input: nums = [0], queries = [[0,0]]
Output: [0]
💡 Note: Single element case: 0 ≤ 0, so 0 XOR 0 = 0.

Constraints

  • 1 ≤ nums.length, queries.length ≤ 105
  • queries[i].length == 2
  • 0 ≤ nums[j], xi, mi ≤ 109

Visualization

Tap to expand
Maximum XOR With Element Constraintnums = [0,1,2,3,4]01234Query: [3, 1] → xi=3, mi=101234≤1 ✓≤1 ✓≤1 ✗≤1 ✗≤1 ✗XOR CalculationsValid elements: {0, 1}0 ⊕ 3 = 31 ⊕ 3 = 2Maximum XOR: 3Answer for query [3,1] = 3
Understanding the Visualization
1
Input
Array nums and queries with [xi, mi] pairs
2
Filter
For each query, find elements ≤ mi
3
Maximize XOR
Compute maximum XOR of xi with valid elements
Key Takeaway
🎯 Key Insight: Use trie structure to efficiently maximize XOR while respecting value constraints
Asked in
Google 15 Microsoft 12 Amazon 8 Facebook 6
28.0K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen