Maximum XOR for Each Query

medium prefix xor bit manipulation array

Problem

Given a sorted array nums of n non-negative integers and an integer maximumBit, perform n queries. For query i: pick k < 2maximumBit that maximizes nums[0] XOR … XOR nums[last] XOR k over the current array, record that k in answer[i], then drop the last element. Return answer.

Because XOR with a free k can flip any bits below maximumBit, the maximum is always all-ones 2maximumBit − 1, and the best k is the current prefix XOR flipped against that mask.

Inputnums = [0,1,1,3], maximumBit = 2
Output[0,3,2,3]
XOR of [0,1,1,3] is 3; with mask 3, k = 3 ^ 3 = 0. Remove 3 → XOR of [0,1,1] is 0; k = 0 ^ 3 = 3, and so on.

def getMaximumXor(nums, maximumBit):
    mask = (1 << maximumBit) - 1       # all-ones target 2^bit - 1
    total = 0
    for v in nums:                     # XOR of the whole array
        total ^= v
    answer = []
    for v in reversed(nums):           # query order: drop last each time
        answer.append(total ^ mask)    # k that flips prefix XOR to all ones
        total ^= v                     # remove last element for next query
    return answer
function getMaximumXor(nums, maximumBit) {
  const mask = (1 << maximumBit) - 1;     // all-ones target 2^bit - 1
  let total = 0;
  for (const v of nums) total ^= v;       // XOR of the whole array
  const answer = [];
  for (let i = nums.length - 1; i >= 0; i--) {
    answer.push(total ^ mask);            // k that flips prefix XOR to all ones
    total ^= nums[i];                     // remove last element for next query
  }
  return answer;
}
int[] getMaximumXor(int[] nums, int maximumBit) {
    int mask = (1 << maximumBit) - 1;        // all-ones target 2^bit - 1
    int total = 0;
    for (int v : nums) total ^= v;          // XOR of the whole array
    int n = nums.length;
    int[] answer = new int[n];
    for (int i = 0; i < n; i++) {
        answer[i] = total ^ mask;           // k flips prefix XOR to all ones
        total ^= nums[n - 1 - i];           // remove last element
    }
    return answer;
}
vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {
    int mask = (1 << maximumBit) - 1;        // all-ones target 2^bit - 1
    int total = 0;
    for (int v : nums) total ^= v;          // XOR of the whole array
    int n = nums.size();
    vector<int> answer(n);
    for (int i = 0; i < n; i++) {
        answer[i] = total ^ mask;           // k flips prefix XOR to all ones
        total ^= nums[n - 1 - i];           // remove last element
    }
    return answer;
}
Time: O(n) Space: O(n) for the output (O(1) extra)