Maximum XOR With an Element From Array Problem
Description
LeetCode Problem 1707.
You are given an array nums consisting of non-negative integers. You are also given a queries array, where queries[i] = [x_i, m_i].
The answer to the i^th query is the maximum bitwise XOR value of x_i and any element of nums that does not exceed m_i. In other words, the answer is max(nums[j] XOR x_i) for all j such that nums[j] <= m_i. If all elements in nums are larger than m_i, then the answer is -1.
Return an integer array answer where answer.length == queries.length and answer[i] is the answer to the i^th query.
Example 1:
Input: nums = [0,1,2,3,4], queries = [[3,1],[1,3],[5,6]]
Output: [3,3,7]
Explanation:
1) 0 and 1 are the only two integers not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2. The larger of the two is 3.
2) 1 XOR 2 = 3.
3) 5 XOR 2 = 7.
Example 2:
Input: nums = [5,2,4,6,6,3], queries = [[12,4],[8,1],[6,3]]
Output: [15,-1,5]
Constraints:
1 <= nums.length, queries.length <= 10^5queries[i].length == 20 <= nums[j], x_i, m_i <= 10^9
Solution
Approach: Offline Queries + Binary Trie
The queries are independent, so we may answer them in any order. Sort nums ascending, and process the queries in ascending order of m_i.
Keep a binary trie of numbers inserted so far, with a pointer j into nums. For a query [x_i, m_i], insert nums[j] while nums[j] <= m_i. Now the trie holds exactly the elements allowed for this query. Walk down from the highest bit, preferring the child with the opposite bit of x_i so that bit of the XOR becomes 1. If the trie is empty, the answer is -1.
Complexity: O(n log n + q log q + (n + q) log M) time and O(n log M) space, where n is the length of nums, q the number of queries and M the largest value (M <= 10^9).
class Trie:
__slots__ = ["children"]
def __init__(self):
self.children = [None] * 2
def insert(self, x: int):
node = self
for i in range(30, -1, -1):
v = x >> i & 1
if node.children[v] is None:
node.children[v] = Trie()
node = node.children[v]
def search(self, x: int) -> int:
node = self
ans = 0
for i in range(30, -1, -1):
v = x >> i & 1
if node.children[v ^ 1]:
ans |= 1 << i
node = node.children[v ^ 1]
elif node.children[v]:
node = node.children[v]
else:
return -1
return ans
class Solution:
def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]:
trie = Trie()
nums.sort()
j, n = 0, len(queries)
ans = [-1] * n
for i, (x, m) in sorted(zip(range(n), queries), key=lambda x: x[1][1]):
while j < len(nums) and nums[j] <= m:
trie.insert(nums[j])
j += 1
ans[i] = trie.search(x)
return ans