Open In App

Count of pairs whose bitwise AND is a power of 2

Last Updated : 24 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of N positive integers. The task is to find the number of pairs whose Bitwise AND value is a power of 2.
Examples: 
 

Input: arr[] = {2, 1, 3, 4} 
Output:
Explanation: 
There are 2 pairs (2, 3) and (1, 3) in this array whose Bitwise AND values are: 
1. (2 & 3) = 1 = (20
2. (1 & 3) = 1 = (20).
Input: arr[] = {6, 4, 2, 3} 
Output:
Explanation: 
There are 4 pairs (6, 4), (6, 2), (6, 3), (2, 3) whose Bitwise and is power of 2. 
 

 

Approach 1 : For each possible pair in the given array, the idea to check whether Bitwise AND of each pairs of elements is perfect power of 2 or not. If “Yes” then count this pair Else check for the next pair.
Below is the implementation of the above approach:
 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if x is power of 2
bool check(int x)
{
    // Returns true if x is a power of 2
    return x && (!(x & (x - 1)));
}
 
// Function to return the
// number of valid pairs
int count(int arr[], int n)
{
    int cnt = 0;
 
    // Iterate for all possible pairs
    for (int i = 0; i < n - 1; i++) {
 
        for (int j = i + 1; j < n; j++) {
 
            // Bitwise and value of
            // the pair is passed
            if (check(arr[i]
                      & arr[j]))
                cnt++;
        }
    }
 
    // Return the final count
    return cnt;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 6, 4, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << count(arr, n);
    return 0;
}


Java




// Java program for the above approach
class GFG{
 
// Method to check if x is power of 2
static boolean check(int x)
{
 
    // First x in the below expression
    // is for the case when x is 0
    return x != 0 && ((x & (x - 1)) == 0);
}
 
// Function to return the
// number of valid pairs
static int count(int arr[], int n)
{
    int cnt = 0;
 
    // Iterate for all possible pairs
    for(int i = 0; i < n - 1; i++)
    {
       for(int j = i + 1; j < n; j++)
       {
           
          // Bitwise and value of
          // the pair is passed
          if (check(arr[i] & arr[j]))
              cnt++;
       }
    }
     
    // Return the final count
    return cnt;
}
 
 
// Driver Code
public static void main(String[] args)
{
     
    // Given array arr[]
    int arr[] = new int[]{ 6, 4, 2, 3 };
 
    int n = arr.length;
     
    // Function call
    System.out.print(count(arr, n));
}
}
 
// This code is contributed by Pratima Pandey


Python3




# Python3 program for the above approach
 
# Function to check if x is power of 2
def check(x):
     
    # Returns true if x is a power of 2
    return x and (not(x & (x - 1)))
 
# Function to return the
# number of valid pairs
def count(arr, n):
     
    cnt = 0
 
    # Iterate for all possible pairs
    for i in range(n - 1):
        for j in range(i + 1, n):
 
            # Bitwise and value of
            # the pair is passed
            if check(arr[i] & arr[j]):
                cnt = cnt + 1
 
    # Return the final count
    return cnt
 
# Given array
arr = [ 6, 4, 2, 3 ]
n = len(arr)
 
# Function Call
print(count(arr, n))
 
# This code is contributed by divyeshrabadiya07


C#




// C# program for the above approach
using System;
class GFG{
 
// Method to check if x is power of 2
static bool check(int x)
{
     
    // First x in the below expression
    // is for the case when x is 0
    return x != 0 && ((x & (x - 1)) == 0);
}
 
// Function to return the
// number of valid pairs
static int count(int []arr, int n)
{
    int cnt = 0;
 
    // Iterate for all possible pairs
    for(int i = 0; i < n - 1; i++)
    {
       for(int j = i + 1; j < n; j++)
       {
            
          // Bitwise and value of
          // the pair is passed
          if (check(arr[i] & arr[j]))
              cnt++;
       }
    }
     
    // Return the final count
    return cnt;
}
 
// Driver Code
public static void Main()
{
     
    // Given array arr[]
    int []arr = new int[]{ 6, 4, 2, 3 };
 
    int n = arr.Length;
     
    // Function call
    Console.Write(count(arr, n));
}
}
 
// This code is contributed by Code_Mech


Javascript




<script>
 
// JavaScript program to implement
// the above approach
 
// Method to check if x is power of 2
function check(x)
{
   
    // First x in the below expression
    // is for the case when x is 0
    return x != 0 && ((x & (x - 1)) == 0);
}
   
// Function to return the
// number of valid pairs
function count(arr, n)
{
    let cnt = 0;
   
    // Iterate for all possible pairs
    for(let i = 0; i < n - 1; i++)
    {
       for(let j = i + 1; j < n; j++)
       {
             
          // Bitwise and value of
          // the pair is passed
          if (check(arr[i] & arr[j]))
              cnt++;
       }
    }
       
    // Return the final count
    return cnt;
}
 
// Driver code
    // Given array arr[]
    let arr = [ 6, 4, 2, 3 ];
   
    let n = arr.length;
       
    // Function call
    document.write(count(arr, n));
 
// This code is contributed by susmitakundugoaldanga.
</script>


Output

4



Time Complexity: O(N2
Auxiliary Space: O(1)
 

Approach 2: To optimize the above approach, we can use a hash map to store the frequency of each integer in the array. Then, we can iterate through each integer i in the array and check if it is present in the hash map. If it is present, we can iterate through each integer j in the array from i to the maximum value in the array and check if it is present in the hash map. If it is present, we can find their bitwise AND using the “&” operator and check if the result has only one set bit. If it does, we can count this pair.

C++




#include <bits/stdc++.h>
using namespace std;
 
long long countPairs(int arr[], int n)
{
    long long ans = 0, mx = 0;
   
    // create a hash map to store the frequency of each
    // integer in the array
    unordered_map<int, int> mp;
    for (int i = 0; i < n; i++) {
        int ai = arr[i];
        // update the frequency of each integer in the
        // hash map
        mp[ai]++;
        // find the maximum value in the array
        mx = max(mx, (long long)ai);
    }
    // iterate through each integer i from 0 to mx
    for (int i = 0; i <= mx; ++i)
    {
       
        // if i is not present in the hash map, skip to
        // the next integer
        if (mp.find(i) == mp.end())
            continue;
       
        // iterate through each integer j from i to mx
        for (int j = i; j <= mx; ++j)
        {
           
            // if j is not present in the hash map, skip
            // to the next integer
            if (mp.find(j) == mp.end())
                continue;
           
            // check if the bitwise AND of i and j has
            // only one set bit
            if (__builtin_popcount(i & j) == 1)
            {
               
                // if i is equal to j, add the product
                // of nCr(mp.get(i), 2) to the answer
                if (i == j)
                    ans += ((long long)mp[i] * (mp[i] - 1))
                           / 2;
               
                // if i is not equal to j, add the
                // product of mp.get(i) and mp.get(j) to
                // the answer
                else
                    ans += ((long long)mp[i]) * mp[j];
            }
        }
    }
    // return the answer
    return ans;
}
 
// Driver Code
int main()
{
    // Given array arr[]
    int arr[] = { 6, 4, 2, 3 };
 
    int n = sizeof(arr) / sizeof(arr[0]);
 
    // Function call
    cout << countPairs(arr, n);
    return 0;
}
 
// This code is contributed by Prajwal Kandekar


Java




import java.util.*;
class Main {
    public static long countPairs(int[] arr, int n)
    {
 
        long ans = 0, mx = 0;
        // create a hash map to store the frequency of each
        // integer in the array
        Map<Integer, Integer> mp = new HashMap<>();
        for (int ai : arr) {
            // update the frequency of each integer in the
            // hash map
            mp.put(ai, mp.getOrDefault(ai, 0) + 1);
            // find the maximum value in the array
            mx = Math.max(mx, ai);
        }
        // iterate through each integer i from 0 to mx
        for (int i = 0; i <= mx; ++i) {
            // if i is not present in the hash map, skip to
            // the next integer
            if (!mp.containsKey(i))
                continue;
            // iterate through each integer j from i to mx
            for (int j = i; j <= mx; ++j) {
                // if j is not present in the hash map, skip
                // to the next integer
                if (!mp.containsKey(j))
                    continue;
                // check if the bitwise AND of i and j has
                // only one set bit
                if (Long.bitCount(i & j) == 1) {
                    // if i is equal to j, add the product
                    // of nCr(mp.get(i), 2) to the answer
                    if (i == j)
                        ans += ((long)mp.get(i)
                                * (mp.get(i) - 1))
                               / 2;
                    // if i is not equal to j, add the
                    // product of mp.get(i) and mp.get(j) to
                    // the answer
                    else
                        ans += ((long)mp.get(i))
                               * mp.get(j);
                }
            }
        }
        // return the answer
        return ans;
    }
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array arr[]
        int arr[] = new int[] { 6, 4, 2, 3 };
 
        int n = arr.length;
 
        // Function call
        System.out.print(countPairs(arr, n));
    }
}


Python3




from typing import List
from collections import defaultdict
 
def countPairs(arr: List[int], n: int) -> int:
    # Initialize answer and maximum value in the array
    ans, mx = 0, 0
    # Create a defaultdict to store the frequency of each integer in the array
    mp = defaultdict(int)
    # Iterate through each integer in the array
    for ai in arr:
        # Update the frequency of each integer in the defaultdict
        mp[ai] += 1
        # Update the maximum value in the array
        mx = max(mx, ai)
    # Iterate through each integer i from 0 to mx
    for i in range(mx+1):
        # If i is not present in the defaultdict, skip to the next integer
        if i not in mp:
            continue
        # Iterate through each integer j from i to mx
        for j in range(i, mx+1):
            # If j is not present in the defaultdict, skip to the next integer
            if j not in mp:
                continue
            # Check if the bitwise AND of i and j has only one set bit
            if bin(i & j).count('1') == 1:
                # If i is equal to j, add the product of nCr(mp.get(i), 2)
                # to the answer
                if i == j:
                    ans += (mp[i] * (mp[i]-1)) // 2
                # If i is not equal to j, add the product of mp.get(i)
                # and mp.get(j) to the answer
                else:
                    ans += mp[i] * mp[j]
    # Return the answer
    return ans
 
# Driver code
arr = [6, 4, 2, 3]
n = len(arr)
print(countPairs(arr, n))


C#




using System;
using System.Collections.Generic;
 
public class GFG
{
    public static long CountPairs(int[] arr, int n)
    {
        long ans = 0, mx = 0;
 
        // create a dictionary to store the frequency of each integer in the array
        Dictionary<int, int> mp = new Dictionary<int, int>();
        for (int i = 0; i < n; i++)
        {
            int ai = arr[i];
            // update the frequency of each integer in the dictionary
            if (mp.ContainsKey(ai))
                mp[ai]++;
            else
                mp.Add(ai, 1);
            // find the maximum value in the array
            mx = Math.Max(mx, (long)ai);
        }
        // iterate through each integer i from 0 to mx
        for (int i = 0; i <= mx; ++i)
        {
 
            // if i is not present in the dictionary, skip to the next integer
            if (!mp.ContainsKey(i))
                continue;
 
            // iterate through each integer j from i to mx
            for (int j = i; j <= mx; ++j)
            {
 
                // if j is not present in the dictionary, skip to the next integer
                if (!mp.ContainsKey(j))
                    continue;
 
                // check if the bitwise AND of i and j has only one set bit
                if (CountSetBits(i & j) == 1)
                {
 
                    // if i is equal to j, add the product of nCr(mp[i], 2) to the answer
                    if (i == j)
                        ans += ((long)mp[i] * (mp[i] - 1)) / 2;
 
                    // if i is not equal to j, add the product of mp[i] and mp[j] to the answer
                    else
                        ans += ((long)mp[i]) * mp[j];
                }
            }
        }
        // return the answer
        return ans;
    }
 
    // Function to count the number of set bits in an integer
    public static int CountSetBits(int num)
    {
        int count = 0;
        while (num > 0)
        {
            count += num & 1;
            num >>= 1;
        }
        return count;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        // Given array arr[]
        int[] arr = { 6, 4, 2, 3 };
 
        int n = arr.Length;
 
        // Function call
        Console.WriteLine(CountPairs(arr, n));
    }
}


Javascript




function countPairs(arr) {
    let ans = 0;
    let mx = 0;
 
    // create a map to store the frequency of each integer in the array
    const mp = new Map();
    for (let i = 0; i < arr.length; i++) {
        const ai = arr[i];
        // update the frequency of each integer in the map
        mp.set(ai, (mp.get(ai) || 0) + 1);
        // find the maximum value in the array
        mx = Math.max(mx, ai);
    }
 
    // iterate through each integer i from 0 to mx
    for (let i = 0; i <= mx; i++) {
        // if i is not present in the map, skip to the next integer
        if (!mp.has(i)) {
            continue;
        }
 
        // iterate through each integer j from i to mx
        for (let j = i; j <= mx; j++) {
            // if j is not present in the map, skip to the next integer
            if (!mp.has(j)) {
                continue;
            }
 
            // check if the bitwise AND of i and j has only one set bit
            if (countSetBits(i & j) === 1) {
                // if i is equal to j, add the product of nCr(mp.get(i), 2) to the answer
                if (i === j) {
                    ans += (mp.get(i) * (mp.get(i) - 1)) / 2;
                }
                // if i is not equal to j, add the product of mp.get(i) and mp.get(j) to the answer
                else {
                    ans += mp.get(i) * mp.get(j);
                }
            }
        }
    }
 
    // return the answer
    return ans;
}
 
// Helper function to count the number of set bits in a number
function countSetBits(num) {
    let count = 0;
    while (num > 0) {
        count += num & 1;
        num >>= 1;
    }
    return count;
}
 
// Driver code
const arr = [6, 4, 2, 3];
console.log(countPairs(arr));
 
// This code is contributed by - Dwaipayan Bandyopadhyay


Output :

4

Time Complexity: O(max(n, mx2)), where n and mx are the size of the array and maximum element in the array respectively.
Auxiliary Space: O(N) 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads