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 INPUT nums array (sorted): 0 [0] 1 [1] 1 [2] 3 [3] maximumBit = 2 max k = 2^2 - 1 = 3 Binary Values: 0 = 00 1 = 01 1 = 01 3 = 11 Total XOR = 0^1^1^3 = 3 (binary: 11) mask = 2^2 - 1 = 3 ALGORITHM STEPS 1 Compute prefix XOR xor = 0^1^1^3 = 3 2 Create mask mask = (1 << 2) - 1 = 3 3 Find k = xor XOR mask k flips bits to maximize 4 Remove last, repeat xor ^= nums[i] to undo Iterations: i=3: xor=3, k=3^3=0 i=2: xor=3^3=0, k=0^3=3 i=1: xor=0^1=1, k=1^3=2 i=0: xor=1^1=0, k=0^3=3 Result: [0,3,2,3] FINAL RESULT Answer Array: 0 3 2 3 Verification: Query 1: 0^1^1^3^0=3 (11) OK Query 2: 0^1^1^3=3 (11) OK Query 3: 0^1^2=3 (11) OK Query 4: 0^3=3 (11) OK All maximize to 3 (all 1s) Complexity: Time: O(n) - single pass Space: O(n) - output array Output: [0,3,2,3] Key Insight: To maximize XOR result, we need k that flips all bits of the current XOR to 1s within the maximumBit range. The optimal k = currentXOR XOR mask, where mask = 2^maximumBit - 1 (all 1s). This guarantees maximum value. By processing backwards and using XOR's self-inverse property, we efficiently "remove" elements: xor ^= nums[i]. TutorialsPoint - Maximum XOR for Each Query | Single Pass Optimal Solution
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