![]() |
VOOZH | about |
Given an integer array arr[] of size N, the task is to count the number of pairs whose BITWISE AND and BITWISE XOR are equal.
Examples:
Input: N = 3, arr[] = [0, 0, 1]
Output: 1
Explanation: All possible pairs from the array are pair = [(0, 0), (0, 1), (1, 0)].
- we can see that pair = (0, 0), 0&0 == 0 and 0^0 == 0 this pair stratified the given condition so, we increase our answer by += 1
- for pair = (0, 1), 0&1 == 0 and 0^1 == 1, we can see that these are not equal we can't increase our ans.
- we check for last also, in last also they are not equal.
So, our answer is 1. Because only one condition stratified the given condition.
Input: N = 4, arr[] = {1, 2, 4, 8}
Output: 0
Explanation: There are no pairs satisfying the condition.
Approach: This can be solved with the following idea:
The idea behind this approach is that we can use a dictionary to count the frequency of each element in the array. Then, we can iterate through all possible pairs of elements and check if their bitwise XOR is equal to their bitwise AND. If it is, we add the product of their frequencies to a counter. Finally, we return half the value of the counter since each pair is counted twice.
Below are the steps involved in the implementation of the code:
Below is the implementation of the code:
1
Time complexity: O(n2)
Auxiliary Space: O(n)