Naive Approach: For the brute force approach to solve this problem, please refer to the SET 1 of this article.
Time Complexity: O(N*N) Auxiliary Space: O(1)
Efficient Approach: The efficient approach to solve this problem is based on following observation:
The observation is that if the index of MSB ( Most Significant bit, also known as leftmost set bit), of any two elements is the same then it is guaranteed that the bitwise XOR of those two elements is less than their bitwise AND ., because 1^1=0, it will unset the MSB. while 1&1=1, MSB will remain set.
If a = 1010, b = 1000,
Then a & b= 1000 and a ^ b = 0010
So if the MSB index is the same in both then their bitwise XOR will always be less than bitwise AND . Vice versa if the MSB index is different then their bitwise XOR value will be greater than the bitwise AND value. Consider the below example to understand this sentence.
Follow the below steps to solve this problem:
Construct an MSB array, MSB[ i ] will represent the count of the elements whose MSB bit’s index is i.
Remove (MSB[ i ]*(MSB[ i ]-1))/2 from total . Because the pair whose MSB is same is not a valid pair .
Return the valid count.
Below is the Implementation of the above approach:
Please Login to comment...