Maximum XOR for Each Query - 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 < 2maximumBitsuch thatnums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR kis maximized.kis the answer to theithquery. - Remove the last element from the current array
nums.
Return an array answer, where answer[i] is the answer to the ith query.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [0,1,1,3], maximumBit = 2
›
Output:
[0,3,2,3]
💡 Note:
Query 1: XOR of [0,1,1,3] = 3, optimal k = 0 (3⊕0 = 3, maximum for 2 bits). Query 2: XOR of [0,1,1] = 0, optimal k = 3 (0⊕3 = 3). Query 3: XOR of [0,1] = 1, optimal k = 2 (1⊕2 = 3). Query 4: XOR of [0] = 0, optimal k = 3 (0⊕3 = 3).
Example 2 — Single Element
$
Input:
nums = [2], maximumBit = 3
›
Output:
[5]
💡 Note:
XOR of [2] = 2 (binary: 010). Maximum value with 3 bits is 7 (binary: 111). Optimal k = 2⊕7 = 5 (binary: 101), giving result 2⊕5 = 7.
Example 3 — Larger maximumBit
$
Input:
nums = [0,1,2,2,5,7], maximumBit = 3
›
Output:
[4,3,6,4,6,7]
💡 Note:
Each query finds k that maximizes XOR with current subarray. The maximum possible result is always 2^maximumBit - 1 = 7.
Constraints
- nums.length == n
- 1 ≤ n ≤ 105
- 1 ≤ maximumBit ≤ 20
- 0 ≤ nums[i] < 2maximumBit
- nums is sorted in ascending order
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array [0,1,1,3] with maximumBit=2
2
Process
Find k that maximizes XOR, then remove last element
3
Output
Array [0,3,2,3] of optimal k values
Key Takeaway
🎯 Key Insight: To maximize A⊕k, set k = A⊕(all 1s within maximumBit range)
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code