Maximum XOR With an Element From Array
Problem Statement
You get a list of non-negative integers nums, and a list of queries. Each query is a pair [x, m].
For each query, look only at the numbers in nums that are not larger than m (that is, number ≤ m). Among those, find the largest value of number XOR x. If no number in nums is ≤ m, the answer for that query is -1.
Return one answer per query, in the same order as the queries.
nums: a list of non-negative integers. queries: a list of pairs [x, m].
A list with one answer per query, in the original query order.
For [3, 1]: only 0 and 1 are ≤ 1, and 0 XOR 3 = 3 beats 1 XOR 3 = 2. For [1, 3]: 2 XOR 1 = 3 is the best of 0, 1, 2, 3. For [5, 6]: 2 XOR 5 = 7 is the best of all five numbers.
For [12, 4]: the allowed numbers are 2, 4 and 3, and 3 XOR 12 = 15 is the best. For [8, 1]: no number is ≤ 1, so the answer is -1. For [6, 3]: the allowed numbers are 2 and 3, and 6 XOR 3 = 5.
- • 1 ≤ nums.length, queries.length ≤ 10^5
- • Each query has exactly two numbers: queries[i] = [x, m].
- • 0 ≤ nums[j], x, m ≤ 10^9
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each query, try every number ≤ m and keep the best XOR; O(n · q)
Sort nums and the queries by m; add each number when it becomes allowed; walk the trie per query
For a query [x, m], look at every number in nums. Skip the numbers above m. Keep the largest number XOR x among the rest. If nothing is allowed, the best value stays -1.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Trie translate into production architectures and low-level memory mechanics.