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:

  1. Find the optimal value k: Choose a non-negative integer k < 2maximumBit such that nums[0] XOR nums[1] XOR ... XOR nums[nums.length-1] XOR k is maximized.
  2. 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
XOR Maximization Visual GuideStep 1: Array XORXOR all elementsStep 2: Find kk = XOR โŠ• maxValStep 3: ResultMaximum XORBinary Example: nums=[0,1,1,3], maximumBit=2Array XOR:00 โŠ• 01 โŠ• 01 โŠ• 11 = 11 (3)maxVal:11 (3 with 2 bits)Optimal k:11 โŠ• 11 = 00 (0)Result:11 โŠ• 00 = 11 (3) - Maximum!
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

n
2n
โœ“ Linear Growth
Space Complexity
O(1)

Only using constant extra space (excluding result array)

n
2n
โœ“ Linear Space

Constraints

  • nums.length == n
  • 1 โ‰ค n โ‰ค 105
  • 1 โ‰ค maximumBit โ‰ค 20
  • 0 โ‰ค nums[i] < 2maximumBit
  • nums is sorted in ascending order
Asked in
Meta 25 Google 20 Microsoft 15 Amazon 10
28.4K Views
Medium Frequency
~15 min Avg. Time
842 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