Given an array arr[] of size N and an integer K, the task is to find the count of all the ordered pairs (i, j) where i != j, such that ((arr[i] ⊕ arr[j]) & K) = 0. The ⊕ represents bitwise XOR and & represents bitwise AND.
Examples:
Input: arr = [1, 2, 3, 4, 5], K = 3
Output: 2
Explanation: There are 2 pairs satisfying the condition.
These pairs are: (1, 5) and (5, 1)Input: arr = [5, 9, 24], K = 7
Output: 0
Explanation: No such pair satisfying the condition exists.
Approach: The given problem can be solved with the help of the following idea:
Using distributive property, we can write ((arr[i] ⊕ arr[j]) & K) = ((arr[i] & K) ⊕ (arr[j] & K)).
Since for ((arr[i] & K) ⊕ (arr[j] & K)) = 0, these two terms (arr[i] & K) and (arr[j] & K) must be equal.
Follow the below steps to solve the problem:
- Create a map and an answer variable (say Res = 0).
- Traverse the array and insert (arr[i] & K) to map with its count.
- Now, traverse the map and for each entry if there are X such occurrences then possible pairs = X*(X-1). So add that to the value Res.
- Return Res as the required answer.
Below is the implementation of the above approach:
C++
|
Time Complexity: O(N)
Auxiliary Space: O(N)