VOOZH about

URL: https://www.geeksforgeeks.org/dsa/bitwise-and-and-xor-pair-counting/

⇱ Bitwise AND and XOR pair counting - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Bitwise AND and XOR pair counting

Last Updated : 16 Sep, 2023

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:

  • Create a dictionary freq to keep track of the frequency of each element in the array.
  • Iterate through all possible pairs of elements in the dictionary.
  • For each pair, check whether their bitwise XOR (^) is equal to their bitwise AND (&).
  • If the condition is true, add the product of the frequencies of the two elements in the pair to a counter.
  • After iterating through all pairs, return half the value of the counter since each pair is counted twice.

Below is the implementation of the code:


Output
1

Time complexity: O(n2)
Auxiliary Space: O(n)

Comment