LeetCode #1707 Hard

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 with nums[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.

Constraints
  • 1 <= nums.length, queries.length <= 10⁵
  • queries[i].length == 2
  • 0 <= nums[j], xi, mi <= 10⁹
triebit-manipulationoffline-queriessorting
Open on LeetCode ↗
02

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.
How to spot this pattern

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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

5

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def maximizeXor(self, nums, queries):
▶3 nums.sort()
▶4 order = sorted(range(len(queries)), key=lambda i: queries[i][1])
▶5 root = {}
▶6 ans = [-1] * len(queries)
▶7 j = 0
▶8 for i in order:
▶9 x, m = queries[i]
▶10 while j < len(nums) and nums[j] <= m:
▶11 node = root
▶12 for b in range(29, -1, -1):
▶13 node = node.setdefault((nums[j] >> b) & 1, {})
▶14 j += 1
▶15 if not root:
▶16 continue
▶17 node, best = root, 0
▶18 for b in range(29, -1, -1):
▶19 want = ((x >> b) & 1) ^ 1
▶20 if want in node:
▶21 best |= 1 << b
▶22 node = node[want]
▶23 else:
▶24 node = node[want ^ 1]
▶25 ans[i] = best
▶26 return ans
421x00001001201030114100xorsorted by limit#0(3, 1)#1(1, 3)#2(5, 6)answers in input order#0#1#2sort numbers, then queries by limit
nums0, 1, 2, 3, 4sorted
queries3sorted by limit
Each query is (x, limit). The numbers are sorted and written in 3 bits, and the queries are sorted by limit, each keeping its input number #i. In this order the set of allowed numbers only grows, so the dashed limit line will only ever move down.
421x301100001001201030114100≤ 1xorsorted by limit#0(3, 1)#1(1, 3)#2(5, 6)answers in input order#0#1#2limit 1 → let 0, 1 in
query#0x 3, limit 1
let in0, 1
allowed0, 1
The line moves down past every number that is at most 1. The trie now holds exactly the numbers this query may use. All of them start as candidates.
421x301100001001201030114100≤ 1xor00sorted by limit#0(3, 1)#1(1, 3)#2(5, 6)answers in input order#0#1#2bit worth 4: x has 0, want 1 → none, take 0
bit4
x bit0
xor bit0
best so far0
No candidate has a 1 in this column, so the XOR bit must be 0. Every candidate has 0 here, so all of them stay.
421x301100001001201030114100≤ 1xor201sorted by limit#0(3, 1)#1(1, 3)#2(5, 6)answers in input order#0#1#2bit worth 2: x has 1, want 0 → 0, 1 have it
bit2
x bit1
xor bit1
best so far2
A candidate with a 0 here makes this XOR bit 1, worth 2, more than all the lower bits together can add (1). So keep only 0, 1 and drop the rest.
421x301100001001201030114100≤ 1xor3011sorted by limit#0(3, 1)#1(1, 3)#2(5, 6)answers in input order#0#1#2bit worth 1: x has 1, want 0 → 0 has it
bit1
x bit1
xor bit1
best so far3
A candidate with a 0 here makes this XOR bit 1, worth 1. So keep only 0 and drop the rest.
421x301100001001201030114100≤ 1xor3011sorted by limit#0(3, 1)3#1(1, 3)#2(5, 6)answers in input order#0#1#2query #0 → 3 XOR 0 is 3
query#0
partner0
answer3
The walk ends on 0, the allowed number that differs from 3 at the highest bits. Its answer 3 goes into slot #0, the query's place in the input, not its place in the sorted list.
421x100100001001201030114100≤ 3xorsorted by limit#0(3, 1)3#1(1, 3)#2(5, 6)answers in input order#0#1#2limit 3 → let 2, 3 in
query#1x 1, limit 3
let in2, 3
allowed0, 1, 2, 3
The line moves down past every number that is at most 3. The trie now holds exactly the numbers this query may use, and the ones let in for earlier queries stay, because their limits were smaller. All of them start as candidates.
421x100100001001201030114100≤ 3xor00sorted by limit#0(3, 1)3#1(1, 3)#2(5, 6)answers in input order#0#1#2bit worth 4: x has 0, want 1 → none, take 0
bit4
x bit0
xor bit0
best so far0
No candidate has a 1 in this column, so the XOR bit must be 0. Every candidate has 0 here, so all of them stay.
421x100100001001201030114100≤ 3xor201sorted by limit#0(3, 1)3#1(1, 3)#2(5, 6)answers in input order#0#1#2bit worth 2: x has 0, want 1 → 2, 3 have it
bit2
x bit0
xor bit1
best so far2
A candidate with a 1 here makes this XOR bit 1, worth 2, more than all the lower bits together can add (1). So keep only 2, 3 and drop the rest.
421x100100001001201030114100≤ 3xor3011sorted by limit#0(3, 1)3#1(1, 3)#2(5, 6)answers in input order#0#1#2bit worth 1: x has 1, want 0 → 2 has it
bit1
x bit1
xor bit1
best so far3
A candidate with a 0 here makes this XOR bit 1, worth 1. So keep only 2 and drop the rest.
421x100100001001201030114100≤ 3xor3011sorted by limit#0(3, 1)3#1(1, 3)3#2(5, 6)answers in input order#0#1#2query #1 → 1 XOR 2 is 3
query#1
partner2
answer3
The walk ends on 2, the allowed number that differs from 1 at the highest bits. Its answer 3 goes into slot #1, the query's place in the input, not its place in the sorted list.
421x510100001001201030114100≤ 6xorsorted by limit#0(3, 1)3#1(1, 3)3#2(5, 6)answers in input order#0#1#2limit 6 → let 4 in
query#2x 5, limit 6
let in4
allowed0, 1, 2, 3, 4
The line moves down past every number that is at most 6. The trie now holds exactly the numbers this query may use, and the ones let in for earlier queries stay, because their limits were smaller. All of them start as candidates.
421x510100001001201030114100≤ 6xor41sorted by limit#0(3, 1)3#1(1, 3)3#2(5, 6)answers in input order#0#1#2bit worth 4: x has 1, want 0 → 0, 1, 2, 3 have it
bit4
x bit1
xor bit1
best so far4
A candidate with a 0 here makes this XOR bit 1, worth 4, more than all the lower bits together can add (3). So keep only 0, 1, 2, 3 and drop the rest.
421x510100001001201030114100≤ 6xor611sorted by limit#0(3, 1)3#1(1, 3)3#2(5, 6)answers in input order#0#1#2bit worth 2: x has 0, want 1 → 2, 3 have it
bit2
x bit0
xor bit1
best so far6
A candidate with a 1 here makes this XOR bit 1, worth 2, more than all the lower bits together can add (1). So keep only 2, 3 and drop the rest.
421x510100001001201030114100≤ 6xor7111sorted by limit#0(3, 1)3#1(1, 3)3#2(5, 6)answers in input order#0#1#2bit worth 1: x has 1, want 0 → 2 has it
bit1
x bit1
xor bit1
best so far7
A candidate with a 0 here makes this XOR bit 1, worth 1. So keep only 2 and drop the rest.
421x510100001001201030114100≤ 6xor7111sorted by limit#0(3, 1)3#1(1, 3)3#2(5, 6)7answers in input order#0#1#2query #2 → 5 XOR 2 is 7
query#2
partner2
answer7
The walk ends on 2, the allowed number that differs from 5 at the highest bits. Its answer 7 goes into slot #2, the query's place in the input, not its place in the sorted list.
421x00001001201030114100≤ 6xorsorted by limit#0(3, 1)3#1(1, 3)3#2(5, 6)7answers in input order3#03#17#2answers: 3, 3, 7
answer[3, 3, 7]
Every query was answered in limit order and written back to its own slot, so the list comes out in input order. Each number was let in once, and each query walked 3 bits.
05

Common pitfalls

Answering 0 when no number fits

✗ Wrong
ans = [0] * len(queries)
✓ Right
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

✗ Wrong
B = max(nums).bit_length()
✓ Right
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.

06

Edge cases

A number equal to the limit, e.g. 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.

07

Complexity

Time
O(n log n + q log q)
Space
O(30n + q)
Sorting dominates. After that, each of the n numbers is inserted once and each of the q queries walks once, 30 steps each. The trie has at most 30 nodes per number, and the order array holds q indices.
08

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.