- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# Program to find maximum XOR for each query in Python

Suppose we have an array which is presorted called nums of size n and also have one value b. We want to perform the following query n times −

Search for a non-negative value k < 2^m such that XOR of all elements in nums and k is maximized. So k is the answer to the ith query.

Remove the last element from the current array nums.

We have to find an array answer, where answer[i] is the answer to the ith query.

So, if the input is like nums = [0,1,1,3], m = 2, then the output will be [0,3,2,3], because

nums = [0,1,1,3], k = 0 since 0 XOR 1 XOR 1 XOR 3 XOR 0 = 3.

nums = [0,1,1], k = 3 since 0 XOR 1 XOR 1 XOR 3 = 3.

nums = [0,1], k = 2 since 0 XOR 1 XOR 2 = 3.

nums = [0], k = 3 since 0 XOR 3 = 3.

To solve this, we will follow these steps −

x := 2^m - 1

for i in range 0 to size of nums - 1, do

nums[i] := nums[i] XOR x

x := nums[i]

return nums after reversal

## Example

Let us see the following implementation to get better understanding −

def solve(nums, m): x=2**m-1 for i in range(len(nums)): nums[i]^= x x = nums[i] return(nums[::-1]) nums = [0,1,1,3] m = 2 print(solve(nums, m))

## Input

[0,1,1,3], 2

## Output

[0, 3, 2, 3]

- Related Articles
- Program to find maximum XOR with an element from array in Python
- Program to find minimum interval to include each query in Python
- Program to count number of similar substrings for each query in Python
- Program to find list of elements which are less than limit and XOR is maximum in Python
- Program to find maximum sum by flipping each row elements in Python
- Program to find maximum weighted sum for rotated array in Python
- Program to find k-th largest XOR coordinate value in Python
- Program to find a matrix for each condominium's height is increased to the maximum possible height in Python?
- Program to find XOR sum of all pairs bitwise AND in Python
- Find maximum value in each sublist in Python
- Program to find maximum width ramp in Python
- Program to find maximum erasure value in Python
- Program to find maximum building height in Python
- Program to find maximum in generated array in Python
- Program to find maximum average pass ratio in Python