Skip to content

1829. Maximum XOR for Each Query 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  vector<int> getMaximumXor(vector<int>& nums, int maximumBit) {
    const int mx = (1 << maximumBit) - 1;
    vector<int> ans;
    int xors = 0;

    for (const int num : nums) {
      xors ^= num;
      ans.push_back(xors ^ mx);
    }

    ranges::reverse(ans);
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int[] getMaximumXor(int[] nums, int maximumBit) {
    final int n = nums.length;
    final int mx = (1 << maximumBit) - 1;
    int[] ans = new int[n];
    int xors = 0;

    for (int i = 0; i < n; ++i) {
      xors ^= nums[i];
      ans[n - 1 - i] = xors ^ mx;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def getMaximumXor(self, nums: list[int], maximumBit: int) -> list[int]:
    mx = (1 << maximumBit) - 1
    ans = []
    xors = 0

    for num in nums:
      xors ^= num
      ans.append(xors ^ mx)

    return ans[::-1]