LeetCode 1829: Maximum XOR for Each Query
Problem Description
Explanation:
- We need to find a number
k
such that XOR of all elements in the given array along withk
is maximized. - To maximize XOR, we need to consider the bits at each position in a binary representation.
- Since the array is sorted, we can iterate from the highest bit to the lowest bit.
- For each bit position, we check how many set bits are there in the current prefix XOR of the array. We can then set the bit at that position in
k
to 1 if it helps in maximizing XOR. - Finally, we return the calculated
k
for each query. Solution:
Solutions
class Solution {
public int[] getMaximumXor(int[] nums, int maximumBit) {
int n = nums.length;
int totalXOR = 0;
for (int num : nums) {
totalXOR ^= num;
}
int[] answer = new int[n];
int mask = (1 << maximumBit) - 1;
for (int i = n - 1; i >= 0; i--) {
answer[n - 1 - i] = totalXOR ^ mask;
totalXOR ^= nums[i];
}
return answer;
}
}
Loading editor...