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:

  1. Find a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized. k is the answer to the ith query.
  2. 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
Maximum XOR for Each Query: Find Optimal K Values0113Input: nums=[0,1,1,3], maximumBit=2Query 1: XOR([0,1,1,3]) = 3, k = 3⊕3 = 0Query 2: XOR([0,1,1]) = 0, k = 0⊕3 = 3Query 3: XOR([0,1]) = 1, k = 1⊕3 = 2Query 4: XOR([0]) = 0, k = 0⊕3 = 30323Output: [0,3,2,3]
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)
Asked in
Google 25 Microsoft 18 Amazon 15 Meta 12
32.0K Views
Medium Frequency
~15 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen