Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum XOR for each query in Python
Suppose we have a presorted array called nums of size n and a value m. 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.
Example Walkthrough
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.
Algorithm
To solve this problem, we follow these steps ?
Initialize x := 2^m - 1
For each element in nums, XOR it with x, then update x to the new value
Return the reversed array
Implementation
def solve(nums, m):
x = 2**m - 1
for i in range(len(nums)):
nums[i] ^= x
x = nums[i]
return nums[::-1]
# Test the function
nums = [0, 1, 1, 3]
m = 2
result = solve(nums, m)
print("Input:", [0, 1, 1, 3], "m =", 2)
print("Output:", result)
Input: [0, 1, 1, 3] m = 2 Output: [0, 3, 2, 3]
How It Works
The algorithm works by transforming each element through XOR operations with a mask value that gets updated in each iteration. The mask starts as 2^m - 1, which represents the maximum possible value with m bits. After each XOR operation, the mask becomes the transformed element, creating a chain effect that maximizes the XOR result for subsequent queries.
Step-by-Step Execution
def solve_with_steps(nums, m):
print(f"Initial: nums = {nums}, m = {m}")
x = 2**m - 1
print(f"Initial mask x = {x}")
for i in range(len(nums)):
old_val = nums[i]
nums[i] ^= x
x = nums[i]
print(f"Step {i+1}: {old_val} XOR {2**m - 1 if i == 0 else nums[i-1]} = {nums[i]}, new x = {x}")
result = nums[::-1]
print(f"Final result (reversed): {result}")
return result
# Test with step-by-step output
nums = [0, 1, 1, 3]
m = 2
solve_with_steps(nums, m)
Initial: nums = [0, 1, 1, 3], m = 2 Initial mask x = 3 Step 1: 0 XOR 3 = 3, new x = 3 Step 2: 1 XOR 3 = 2, new x = 2 Step 3: 1 XOR 2 = 3, new x = 3 Step 4: 3 XOR 3 = 0, new x = 0 Final result (reversed): [0, 3, 2, 3]
Conclusion
This algorithm efficiently finds the maximum XOR values for each query by using a cumulative XOR approach with a dynamic mask. The key insight is that reversing the transformed array gives us the optimal k values for each query in the correct order.
