#1707

Maximum XOR With an Element From Array

Hard Offline queries + binary trie

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

For each query [x, m], return the maximum x XOR v over array values v ≤ m, or -1 if no value is ≤ m.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: for each query (x, m), the max x XOR v with v ≤ m.

Why this works: sort the queries by m and insert numbers into the trie only while they're ≤ m; then query as usual.

Example: nums [0,1,2,3,4], query (3, 1)

insert 0, 13 ^ 0 = 3, 3 ^ 1 = 2 → 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Answering queries in input order — you'd have to rebuild the trie for each m.

Solve on LeetCode ↗
Complexity
  • Time: O((n + q) · 30 + n log n + q log q).
  • Space: O(n · 30).
Topic: Trie
🎬 Episode 97: video coming soon