Maximum XOR for Each Query - Problem
You are given a sorted array nums of n non-negative integers and an integer maximumBit. Your task is to perform n queries where each query involves:
- Find the optimal value
k: Choose a non-negative integerk < 2maximumBitsuch thatnums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR kis maximized. - Remove the last element: After finding
k, remove the last element from the current array.
Return an array answer where answer[i] is the answer to the i-th query.
Key Insight: Since we want to maximize the XOR result, we need to find the value k that creates the largest possible binary number when XORed with our current array's XOR.
Input & Output
example_1.py โ Basic Example
$
Input:
nums = [0,1,1,3], maximumBit = 2
โบ
Output:
[0,3,2,3]
๐ก Note:
Query 1: nums=[0,1,1,3], XOR=3, maxVal=3, optimal k=0 gives 3โ0=3. Query 2: nums=[0,1,1], XOR=0, optimal k=3 gives 0โ3=3. Query 3: nums=[0,1], XOR=1, optimal k=2 gives 1โ2=3. Query 4: nums=[0], XOR=0, optimal k=3 gives 0โ3=3.
example_2.py โ Single Element
$
Input:
nums = [2,3,4,7], maximumBit = 3
โบ
Output:
[5,2,6,5]
๐ก Note:
With maximumBit=3, maxVal=7. For each query, we find k that maximizes the XOR result by taking the complement within the 3-bit range.
example_3.py โ Edge Case
$
Input:
nums = [0], maximumBit = 1
โบ
Output:
[1]
๐ก Note:
Single element array with XOR=0. With maximumBit=1, maxVal=1, so optimal k=0โ1=1.
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Array XOR
Find XOR of all elements in current array
2
Find Bit Complement
To maximize result, flip all bits within maximumBit range
3
Update for Next Query
Remove last element by XORing it out
Key Takeaway
๐ฏ Key Insight: To maximize XOR result, use the bitwise complement of the current XOR within the allowed bit range
Time & Space Complexity
Time Complexity
O(n)
Single pass through array with O(1) operations per element
โ Linear Growth
Space Complexity
O(1)
Only using constant extra space (excluding result array)
โ Linear Space
Constraints
- nums.length == n
- 1 โค n โค 105
- 1 โค maximumBit โค 20
- 0 โค nums[i] < 2maximumBit
- nums is sorted in ascending order
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code