Maximum XOR With an Element From Array
Maximum XOR With an Element From Array is LeetCode 1707 (Hard). You get an array nums of non-negative integers and a list of queries, where queries[i] = [xi, mi].
- For each query, return the largest
xi XOR nums[j]among the numbers withnums[j] <= mi. - If no number is at most
mi, that answer is-1. - Return the answers in the order the queries were given.
Both arrays hold up to 10⁵ entries, so scanning all of nums for every query (about 10¹⁰ steps) is too slow. Every value is at most 10⁹, which fits in 30 bits.
- 1 <= nums.length, queries.length <= 10⁵
- queries[i].length == 2
- 0 <= nums[j], xi, mi <= 10⁹
Intuition
Without the limit, this is the classic binary trie: store each number as a path of bits, highest bit first, and walk it for x taking the opposite bit whenever it exists. One high XOR bit outweighs all lower bits together, so that walk finds the best partner.
The limit means each query allows a different set of numbers. The fix is to answer the queries in increasing order of their limit:
- The allowed set only grows: every number that is at most 3 is also at most 6, so nothing ever has to leave the trie.
- One trie serves every query: before a query, insert the numbers that just came under its limit. The trie then holds exactly the allowed numbers.
Maximum XOR queries with an upper limit on the allowed numbers call for offline query processing: when each query only filters a set by a threshold, sort the queries by that threshold and grow one structure instead of building a new one per query. The same idea appears with prefix sums, union-find and segment trees.
Approach
Before reading on, solve the version with no limit: how do you find the best XOR partner for x in a set of numbers? Then ask what order of queries would let you only ever add numbers to that set. Aim for O((n + q) log n).
Sort the numbers and the queries
Sort nums ascending. Sort the query indices by mi, keeping each original index so its answer can be written back in place. Answering out of order is fine, because nobody reads the answers until the end.
Insert every number under the limit
Move a pointer j through nums and insert nums[j] while nums[j] <= mi, as a 30-bit path from bit 29 down to bit 0. Limits never decrease, so each number is inserted once in total and stays allowed for every later query.
Skip the walk when the trie is empty
If nothing has been inserted yet, every number is bigger than mi, so the answer for this query stays -1 and the next query is processed.
Walk the trie, preferring the opposite bit
Start at the root with best = 0. At bit b, the wanted child is the opposite of x's bit. If it exists, go there and add 2^b to best. Otherwise take the other child. A 1 at bit b beats every choice below it, because all lower bits together add up to only 2^b − 1.
Store the answer at the original index
Write best into ans[i], where i is the query's position in the input. The sort changed the order of work, not the order of the output.
Code in Python, C++ and Java
Common pitfalls
Answering 0 when no number fits
ans = [0] * len(queries)
ans = [-1] * len(queries)
A query whose limit is below every number is skipped, so it keeps its starting value. On nums = [5, 6], queries = [[1, 2]] the answer must be -1, but a list of zeros returns [0], which looks like a real XOR.
Sizing the bits from nums alone
B = max(nums).bit_length()
B = 30 # covers every value up to 10⁹
The walk only builds the bits it visits, and x can be far bigger than any number. On nums = [1], queries = [[8, 1]] a 1-bit trie returns 1, losing the 8 that x contributes on its own; the right answer is 8 XOR 1 = 9.
Edge cases
nums = [3], queries = [[4, 3]]The rule is nums[j] <= mi, so 3 is allowed and the answer is 4 XOR 3 = 7. A strict < in the insert loop would skip it and return -1.
Complexity
Maximum XOR With an Element From Array FAQ
Can the queries be answered in the given order, without sorting them?
Yes. Insert every number up front and store in each trie node the smallest number below it. A query with limit m gets -1 if the root's minimum is above m. During the walk it takes the opposite-bit child only if that child exists and its minimum is at most m, and otherwise the same-bit child, which must then hold an allowed number. Each query is still 30 steps.
How is this different from Maximum XOR of Two Numbers in an Array?
That problem (LeetCode 421) uses one fixed set and asks for the best pair inside it, so every number goes into the trie at once. Here each query has its own x and its own limit, and the work is about controlling which numbers are in the trie when each query is walked.