# Program to find maximum XOR with an element from array in Python

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array called nums with non-negative values. We also have another array called queries where queries[i] has a pair (xi, mi). The answer of ith query is the maximum bitwise XOR value of xi and any element of nums that less than or equal to mi. If all elements in nums are larger than mi, then the answer is -1. So we have to find an array answer where size of answer is same as size of query and answer[i] is the answer to the ith query.

So, if the input is like nums = [0,1,2,3,4] queries = [[3,1],[1,3],[5,6]], then the output will be [3,3,7], because

• 0 and 1 are not greater than 1. 0 XOR 3 = 3 and 1 XOR 3 = 2, here larger of these two is 3.

• 1 XOR 2 = 3.

• 5 XOR 2 = 7.

To solve this, we will follow these steps −

• m := size of nums

• n := size of queries

• queries = make a triplet (i, x, limit) for each index i, and pair (x, limit) in queries

• sort queries based on limit

• nums := sort the list nums

• res := an array of size n and fill with 0

• for k in range 31 to 0, decrease by 1, do

• prefixes := a new set

• j := 0

• for each index i and value (x, limit) in queries, do

• while j <= m - 1 and nums[j] <= limit, do

• shift nums[j] to the right k bits and insert into prefixes

• j := j + 1

• if prefixes is empty, then

• res[i] := -1

• otherwise,

• res[i] = quotient of res[i]/2

• target := res[i] XOR 1

• if (x after shifting k bits to right) XOR target is in prefixes, then

• res[i] := target

• return res

## Example

Let us see the following implementation to get better understanding

def solve(nums, queries):
m, n = len(nums), len(queries)
queries = sorted(((i, x, limit) for i, (x, limit) in
enumerate(queries)), key=lambda x: x[2])
nums = sorted(nums)
res = [0] * n
for k in range(31, -1, -1):
prefixes = set()
j = 0
for i, x, limit in queries:
while j <= m - 1 and nums[j] <= limit:
j += 1
if not prefixes:
res[i] = -1
else:
res[i] <<= 1
target = res[i] ^ 1
if (x >> k) ^ target in prefixes:
res[i] = target
return res

nums = [0,1,2,3,4]
queries = [[3,1],[1,3],[5,6]]
print(solve(nums, queries))

## Input

[0,1,2,3,4], [[3,1],[1,3],[5,6]]


## Output

[3, 3, 7]
Updated on 07-Oct-2021 08:15:55