1940. Maximum XOR for Each Query
My accepted Python solution to LeetCode problem 1940, Maximum XOR for Each Query, running in 48ms.
- Difficulty: Medium
- Python
- Runtime 48ms
- Memory 32.9MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 48ms, memory 32.9MB, accepted 2025-12-29.
class Solution:
def getMaximumXor(self, nums: List[int], maximumBit: int) -> List[int]:
# Time: O(n), Space: O(n) for result
# Key insight: XOR all nums to get cumulative XOR
# To maximize XOR with k where k < 2^maximumBit,
# k should flip all bits in the result to make it (2^maximumBit - 1)
n = len(nums)
result = []
# Calculate XOR of all elements
xor_sum = 0
for num in nums:
xor_sum ^= num
# Maximum value with maximumBit bits is (2^maximumBit - 1)
max_val = (1 << maximumBit) - 1
# For each query (starting from full array, removing from end)
for i in range(n):
# To maximize xor_sum XOR k, we want k = max_val XOR xor_sum
# This gives us max_val when XOR'd with xor_sum
k = max_val ^ xor_sum
result.append(k)
# Remove last element for next query
xor_sum ^= nums[n - 1 - i]
return result