given to integers A and B A<=B find XOR of all the elements between them.

Expected Complexity: logN

given to integers A and B A<=B find XOR of all the elements between them.

Expected Complexity: logN

Let us denote f(n) = 1 \oplus 2 \oplus 3 \oplus \dots \oplus n, where \oplus denotes XOR operation

then XOR of all numbers between A and B can be represented by f(B) \oplus f(A-1), because x \oplus x = 0

Now we can find out easily that,

f(n) = \left\{\begin{array}{@{}lr@{}}
n, & \text{n mod 4 = 0}\\
1, & \text{n mod 4 = 1}\\
n+1, & \text{n mod 4 = 2}\\
0, & \text{n mod 4 = 3}
\end{array}\right\}

Time Complexity - O(1)

6 Likes

can anybody help me if the array is given and range is also given …

if array is 1 2 7 4 5

a=3 b=4 ans should be 3 but above solution gives 7 ans.

in this question range means all the no. in that range. suppose a=3 b=7 then this means we have to find 3^4^5^6^7.

for practice this type of question you can follow this link