You have an integer array ‘A’ of the form of [x, x+1, x+2, x+3, …….]. As the array is vast in size, you are given both endpoints of the array, i.e., If you are given two integers, ‘L’ and ‘R’, the array ‘A’ will be [L, L+1, L+2, ……., R-1, R]. Your task is to find the maximum possible value of ‘X’ such that the following two conditions hold.
a ⊕ b = X, where ⊕ denotes bitwise xor operation.
Both numbers ‘a’ and ‘b’ belong to the array ‘A’.
The first line contains 'T', denoting the number of tests.
For each Test :
The only line contains two space-separated integers 'L' and 'R', denoting the endpoints of the array.
Output Format:
For each test, print an integer, denoting the maximum possible xor of two elements from the array.
Note:
You are not required to print the expected output. It has already been taken care of. Just implement the function.
1 <= 'T' <= 10^3
1 <= 'L' <= 'R' <= 10^9
Time Limit: 1 sec
2
8 20
1 3
31
3
For case 1:
The array looks like [8, 9, 10, ….., 18, 19, 20]. From all possible pairs (a, b), pair (15, 16) gives maximum value of xor, which is 15 ⊕ 16 = 31.
For Case 2:
Optimal pair is (2, 3), which gives 2 ⊕ 3 = 3.
2
4 10
4 7
15
3
Can you check for all possible pairs (a, b)?
Approach: Run two loops (nested) to find all possible pairs (a, b) such that (L <= a, b <= R) and calculate (a ⊕ b). Finally, return maximum xor value among all generated pairs.
Algorithm:
O(N ^ 2), where ‘N’ is the number of elements in array ‘A’, i.e. (N = R - L + 1).
We are finding xor value for each possible pair in the given range. Hence overall time complexity becomes O(N ^ 2).
O(1).
We are using only constant space. Hence overall space complexity is O(1).