Problem
You are given a sorted array nums
of n
non-negative integers and an integer maximumBit
. You want to perform the following query n
times:
- Find a non-negative integer
k < 2maximumBit
such thatnums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k
is maximized.k
is the answer to theith
query. - Remove the last element from the current array
nums
.
Return an array answer
, where answer[i]
is the answer to the ith
query.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints
0 <= nums[i] < 2^maximumBit
Solution
Method 1 - Calculate xor of whole array
The goal is to find the value of k
such that the XOR of all elements in nums
and k
is maximized for each query. We are given that k < 2^maximumBit
, so maximum possible value is achieved with (1 << maximumBit) - 1
, meaning all bits within the maximumBit
range are set.
It’s important to note this constraint as well:
0 <= nums[i] < 2^maximumBit
Why is the maximum always 2^maximumBit - 1
?
Given that each element in nums
lies within the range [0, 2^maximumBit - 1]
, after XOR-ing all elements, the resulting value (let’s call it numsXor
) will also be within this range. Because at maximum, this value will be equal to 2 ^ maxBit - 1
.
To maximize the resultant numsXor
output, we can xor
this value with any number within [0, 2^maximumBit - 1]
. The optimal choice is the number which, when XOR-ed with numsXor
, yields 2^maximumBit - 1
.
For maximumBit = 3
, the range is [0, 7]
. To achieve the maximum result when XOR-ing number a
with another number b
, the other number must have opposite bits in each position to ensure all bits are set.
Consider:
|
|
Following this logic, we can always choose a number to maximize XOR to 2^maximumBit - 1
. After computing numsXor
for the original nums
array, subsequent changes involve removing the last element. We update numsXor
by XOR-ing it with the removed element, leveraging the property that XOR-ing an element twice cancels it out. This gives the final answer for each query.
The general idea is:
- Calculate the XOR of all elements in the array
nums
initially, let’s call itnums_xor
. - For each query, calculate the best possible value of
k
that, when XORed withnums_xor
, provides the maximum value. Since we want the result to be the maximum,k
should benums_xor
XOR with all bits set to1
within the range2^maximumBit - 1
(this is2^maximumBit - 1
). - Remove the last element of the array
nums
and updatenums_xor
by XORing it with the removed element.
Video explanation
Here is the video explaining this method in detail. Please check it out:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
wheren
is the number of elements innums
because we are iterating through the list once and performing constant time operations. - 🧺 Space complexity:
O(1)
additional space for calculation, not counting the space of the output array.