Open In App

Bitwise AND and XOR pair counting

Last Updated : 16 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




//C++ implementation
#include<bits/stdc++.h>
using namespace std;
 
// Function to count pairs
void countPairs(int n, int arr[])
{
    // Create an unordered_map to count the
    // frequency of each element in the array
    unordered_map<int, int> freq;
    for (int i = 0; i < n; i++)
    {
        freq[arr[i]]++;
    }
 
    int ans = 0;
 
    // Iterate through all possible pairs
    // of elements in the unordered_map
    for (auto it1 = freq.begin(); it1 != freq.end(); it1++)
    {
        for (auto it2 = freq.begin(); it2 != freq.end(); it2++)
        {
            int i = it1->first;
            int j = it2->first;
 
            // Check if their bitwise XOR
            // is equal to their bitwise AND
            if ((i ^ j) == (i & j))
            {
                // Step 4: Add the product
                // of their frequencies
                // to the counter
                if (i == j)
                {
                    ans += (it1->second) * (it2->second - 1);
                }
                else
                {
                    ans += (it1->second) * (it2->second);
                }
            }
        }
    }
 
    // Return half the value of the counter
    // since each pair is counted twice
    cout << ans / 2 << endl;
}
 
// Driver code
int main()
{
    int n = 3;
    int arr[] = {0, 0, 1};
 
    // Function call
    countPairs(n, arr);
 
    return 0;
}


Java




// Java Implementation
import java.util.*;
import java.lang.*;
import java.io.*;
 
class GFG {
    public static void countPairs(int n, int arr[])
    {
        // Create an unordered_map to count the
        // frequency of each element in the array
        HashMap<Integer, Integer> freq = new HashMap<Integer, Integer>();
        for (int i = 0; i < n; i++)
        {
            freq.put(arr[i], freq.getOrDefault(arr[i], 0) + 1);
        }
 
        int ans = 0;
 
        // Iterate through all possible pairs
        // of elements in the unordered_map
        for (Map.Entry<Integer, Integer> it1 : freq.entrySet())
        {
            for (Map.Entry<Integer, Integer> it2 : freq.entrySet())
            {
                int i = it1.getKey();
                int j = it2.getKey();
 
                // Check if their bitwise XOR
                // is equal to their bitwise AND
                if ((i ^ j) == (i & j))
                {
                    // Step 4: Add the product
                    // of their frequencies
                    // to the counter
                    if (i == j)
                    {
                        ans += (it1.getValue()) * (it2.getValue() - 1);
                    }
                    else
                    {
                        ans += (it1.getValue()) * (it2.getValue());
                    }
                }
            }
        }
 
        // Return half the value of the counter
        // since each pair is counted twice
        System.out.println(ans / 2);
    }
 
    // Driver code
    public static void main (String[] args)
    {
        int n = 3;
        int arr[] = {0, 0, 1};
 
        // Function call
        countPairs(n, arr);
 
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Python




# Python Implementation
 
# Function to count pairs
 
 
def countPairs(n, arr):
 
    # Create a dictionary to count the
    # frequency of each element in
    # the array
    freq = {}
    for i in arr:
        freq[i] = freq.get(i, 0) + 1
 
    ans = 0
 
    # Iterate through all possible pairs
    # of elements in the dictionary
    for i in freq.keys():
        for j in freq.keys():
 
            # Check if their bitwise XOR
            # is equal to their bitwise AND
            if i ^ j == i & j:
 
                # Step 4: Add the product
                # of their frequencies
                # to the counter
                if i == j:
                    ans += freq[i] * (freq[j] - 1)
                else:
                    ans += freq[i] * freq[j]
 
    # Return half the value of the
    # counter since each pair is
    # counted twice
    print(ans // 2)
 
 
# Driver code
n = 3
arr = [0, 0, 1]
 
# Function call
countPairs(n, arr)


C#




// C# implementation of the above approach
using System;
using System.Collections.Generic;
 
public class GFG {
    // Function to count pairs
    static void CountPairs(int n, int[] arr)
    {
        // Create a Dictionary to count the
        // frequency of each element in the array
        Dictionary<int, int> freq
            = new Dictionary<int, int>();
        for (int i = 0; i < n; i++) {
            if (freq.ContainsKey(arr[i])) {
                freq[arr[i]]++;
            }
            else {
                freq[arr[i]] = 1;
            }
        }
 
        int ans = 0;
 
        // Iterate through all possible pairs
        // of elements in the Dictionary
        foreach(var kvp1 in freq)
        {
            foreach(var kvp2 in freq)
            {
                int i = kvp1.Key;
                int j = kvp2.Key;
 
                // Check if their bitwise XOR
                // is equal to their bitwise AND
                if ((i ^ j) == (i & j)) {
                    // Step 4: Add the product
                    // of their frequencies
                    // to the counter
                    if (i == j) {
                        ans += kvp1.Value
                               * (kvp2.Value - 1);
                    }
                    else {
                        ans += kvp1.Value * kvp2.Value;
                    }
                }
            }
        }
 
        // Return half the value of the counter
        // since each pair is counted twice
        Console.WriteLine(ans / 2);
    }
 
    // Driver code
    static void Main()
    {
        int n = 3;
        int[] arr = { 0, 0, 1 };
 
        // Function call
        CountPairs(n, arr);
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




<script>
// Javascript Implementation
 
function countPairs(n, arr) {
    // Create a Map to count the frequency of each element in the array
    const freq = new Map();
    for (let i = 0; i < n; i++) {
        if (!freq.has(arr[i])) {
            freq.set(arr[i], 1);
        } else {
            freq.set(arr[i], freq.get(arr[i]) + 1);
        }
    }
 
    let ans = 0;
 
    // Iterate through all possible pairs of elements in the Map
    for (const [i, freq1] of freq) {
        for (const [j, freq2] of freq) {
            // Check if their bitwise XOR is equal to their bitwise AND
            if ((i ^ j) === (i & j)) {
                // Add the product of their frequencies to the counter
                if (i === j) {
                    ans += freq1 * (freq2 - 1);
                } else {
                    ans += freq1 * freq2;
                }
            }
        }
    }
 
    // Return half the value of the counter since each pair is counted twice
    document.write(Math.floor(ans / 2));
}
 
// Driver code
const n = 3;
const arr = [0, 0, 1];
 
// Function call
countPairs(n, arr);
 
// This code is contributed by Susobhan Akhuli
</script>


Output

1

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads