1707. Maximum XOR With an Element From Array
Description
You are given an array nums
consisting of non-negative integers. You are also given a queries
array, where queries[i] = [xi, mi]
.
The answer to the ith
query is the maximum bitwise XOR
value of xi
and any element of nums
that does not exceed mi
. In other words, the answer is max(nums[j] XOR xi)
for all j
such that nums[j] <= mi
. If all elements in nums
are larger than mi
, then the answer is -1
.
Return an integer arrayanswer
whereanswer.length == queries.length
andanswer[i]
is the answer to theith
query.
Example 1:
Example 2:
Constraints:
1 <= nums.length, queries.length <= 10^5
queries[i].length == 2
0 <= nums[j], xi, mi <= 10^9
Tags
Bit Manipulation, Trie
Solution
For a solution with less complexity, refer to Reference 1.
If there is no restriction mi
for each query, we can obtain the query result by find a number y
in nums
, who shares different bits with xi
as much as possible. To find such y
efficiently, we can build a Trie tree. To take mi
into consideration, we can sort both nums
and queries
first, then for each query, insert elements in nums one by one until nums[j] > mi
. After inserting, if the trie tree is empty, we assign -1 to the result according to the requirement; otherwise we start to find such y
we want.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?