![]() |
VOOZH | about |
You are given a sequence of N integers and Q queries. In each query, you are given two parameters L and R. You have to find the smallest integer X such that 0 <= X < 2^31 and the sum of XOR of x with all elements in range [L, R] is maximum possible.
Examples :
Input : A = {20, 11, 18, 2, 13}
Three queries as (L, R) pairs
1 3
3 5
2 4
Output : 2147483629
2147483645
2147483645
Approach: The binary representation of each element and X, we can observe that each bit is independent and the problem can be solved by iterating over each bit. Now basically for each bit we need to count the number of 1's and 0's in the given range, if the number of 1's are more then you have to set that bit of X to 0 so that the sum is maximum after xor with X else if number of 0's are more then you have to set that bit of X to 1. If the number of 1's and 0's are equal then we can set that bit of X to any one of 1 or 0 because it will not affect the sum, but we have to minimize the value of X so we will take that bit 0.
Now, to optimize the solution we can pre-calculate the count of 1's at each bit position of the numbers up to that position by making a prefix array this will take O(n) time. Now for each query number of 1's will be the number of 1's up to Rth position - number of 1's up to (L-1)th position.
Output :
2147483629 2147483647 2147483629
Time complexity: O(n)
Auxiliary Space: O(n)
Approach 2 :
From the below table you can see that if we are given a number n, our answer would "N-n", where N is all 1s.
And we can get n (which is sum of all integers from A[i] to A[j]) using "prefixSum[j] - prefixSum[i]".
| Number (n) | 1 | 0 | 0 | 1 | 0 | 0 | 1 |
| All 1s (N) | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
| N-n | 0 | 1 | 1 | 0 | 1 | 1 | 0 |
Time complexity: O(n)
Auxiliary Space: O(n)