For me, I first created a frequency array, and also split the input array into two arrays:
an array of even numbers
an array of odd numbers.
I then sorted the two arrays(I will latter on apply binary search), and performed the following steps:
calculate number of odd pairs, “oddPairs” using (n(n+1)/2)-n, and add it to number of even Pairs, “evenPairs”.
calculate number of pairs whose XOR is 0, “zeros” from the frequency array
calculate number of pairs whose XOR is 2, “nparity”, by applying binary search on both even and odd arrays.
And finally subtracting (zeros + nparity) from (oddPairs + evenPairs)
There were a few observations which I made, leading to my decision to apply binary search:
If a is even then a^(a + 2) is 2 only if a/2 is even, and a^(a - 2) is 2 if otherwise.
If a is odd then a^(a + 2) is 2 only if (a+1)/2 is odd, and a^(a - 2) is 2 if otherwise.
So the way I calculated the pairs whose XOR is 2 was by applying binary search separately on each sorted array, starting from the first number a[1] in the array, I would then search for either (a + 2) or (a - 2) depending on the above observations, and then marking all indexes from (a + 2) onwards or (a - 2) onwards as seen, so that those indexes wouldn’t be latter on visited.
Here’s my solution CodeChef: Practical coding for everyone
3)calculate number of pairs whose XOR is 2, “nparity”, by applying binary search on both even and odd arrays.
it requires 2 for loops right(order of n)
https://www.codechef.com/viewsolution/20237335
In my implementation, instead of halving the value at the end. I have decremented the frequency and odd or even before each iteration. So, can anyone point out which case did i miss. Thanks in Advance
No. It requires only 1 for loop. You first take a number a[i]. If it’s even, you divide it by two. If the result of the division is even it means that a[i]^(a[i] + 2) is 2. So you search for (a[i] + 2) using binary search. The search will either return -1 if (a[i] + 2) is not found, or the index of where it occurred. And since our arrays are sorted, we can get the number of times (a[i] + 2) is repeated.
We would have searched for (a[i] - 2) if the result of our division was odd.
On the other hand, if a[i] is odd, then we divide a[i]+2 by 2. If the result is odd, we search for a[i]+2, and if otherwise, we search for a[i]-2.
NOTE: Binary search is what is being applied here, and not linear search. So in the worst case (when there are no pairs whose XOR is 2), then we will have O(NlogN); in the best case (where the a[0] matches with the rest), then we have approximately O(logN).