You are given integer array A of size N and Q queries for every query you are given L,R and X
You are required to determine the value of
(Al xor x)+(A(l+1) xor x)+…(Ar xor x)
Pls share approaches
This was asked in oyo coding round
I’ll leave behind some things that you need to figure out yourself (^_^)
countOfSetBits and countOfUnsetBits can be obtained in O(1) time using the prefix array. I reccomend you to get comfortable with prefix array before approaching this problem.
A = [ 7, 4, 3, 1, 5 ]
L = 2
R = 4
X = 6
Binary Representation of X : 000…00110
nextPowerOfTwo = 1
answer = 0
Lets iterate through each bit :
0th position is unset in X :
answer = answer + (nextPowerOfTwo * countOfSetBits )
answer => 0 + ( 1 * 2) = 2
nextPowerOfTwo = nextPowerOfTwo * 2
1st position is set in X :
answer = answer + (nextPowerOfTwo * countOfUnsetBits )
answer => 2 + ( 2 * 2) = 6
nextPowerOfTwo = nextPowerOfTwo * 2
2nd position is set in X :
answer = answer + (nextPowerOfTwo * countOfUnsetBits )
answer => 6 + ( 4 * 2) = 14
After this, all the positons are unset and hence the maximum value is 14
@akshat_165
I don’t want to be rude, but in competitive programming you can ask for hints and for clarifications, but you also have to use an example to understand. We can’t spoon feed you with examples too. In a competition, no one will come to help you even with hints, so try taking this first step.
What I found out :
for every set bit in x, find the number of corresponding unset bits in present among all the numbers between L to R and for all unset bits in x, find the number of elements having the corresponding element set. Each of these counts can be pre-computed earlier and prefix sum is needed to find count of number of elements has the ith bit set/unset.
You can refer to my code for implementation details. Let