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: 2
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: 4
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++
#include <bits/stdc++.h>
using namespace std;
bool check( int x)
{
return x && (!(x & (x - 1)));
}
int count( int arr[], int n)
{
int cnt = 0;
for ( int i = 0; i < n - 1; i++) {
for ( int j = i + 1; j < n; j++) {
if (check(arr[i]
& arr[j]))
cnt++;
}
}
return cnt;
}
int main()
{
int arr[] = { 6, 4, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << count(arr, n);
return 0;
}
|
Java
class GFG{
static boolean check( int x)
{
return x != 0 && ((x & (x - 1 )) == 0 );
}
static int count( int arr[], int n)
{
int cnt = 0 ;
for ( int i = 0 ; i < n - 1 ; i++)
{
for ( int j = i + 1 ; j < n; j++)
{
if (check(arr[i] & arr[j]))
cnt++;
}
}
return cnt;
}
public static void main(String[] args)
{
int arr[] = new int []{ 6 , 4 , 2 , 3 };
int n = arr.length;
System.out.print(count(arr, n));
}
}
|
Python3
def check(x):
return x and ( not (x & (x - 1 )))
def count(arr, n):
cnt = 0
for i in range (n - 1 ):
for j in range (i + 1 , n):
if check(arr[i] & arr[j]):
cnt = cnt + 1
return cnt
arr = [ 6 , 4 , 2 , 3 ]
n = len (arr)
print (count(arr, n))
|
C#
using System;
class GFG{
static bool check( int x)
{
return x != 0 && ((x & (x - 1)) == 0);
}
static int count( int []arr, int n)
{
int cnt = 0;
for ( int i = 0; i < n - 1; i++)
{
for ( int j = i + 1; j < n; j++)
{
if (check(arr[i] & arr[j]))
cnt++;
}
}
return cnt;
}
public static void Main()
{
int []arr = new int []{ 6, 4, 2, 3 };
int n = arr.Length;
Console.Write(count(arr, n));
}
}
|
Javascript
<script>
function check(x)
{
return x != 0 && ((x & (x - 1)) == 0);
}
function count(arr, n)
{
let cnt = 0;
for (let i = 0; i < n - 1; i++)
{
for (let j = i + 1; j < n; j++)
{
if (check(arr[i] & arr[j]))
cnt++;
}
}
return cnt;
}
let arr = [ 6, 4, 2, 3 ];
let n = arr.length;
document.write(count(arr, n));
</script>
|
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;
unordered_map< int , int > mp;
for ( int i = 0; i < n; i++) {
int ai = arr[i];
mp[ai]++;
mx = max(mx, ( long long )ai);
}
for ( int i = 0; i <= mx; ++i)
{
if (mp.find(i) == mp.end())
continue ;
for ( int j = i; j <= mx; ++j)
{
if (mp.find(j) == mp.end())
continue ;
if (__builtin_popcount(i & j) == 1)
{
if (i == j)
ans += (( long long )mp[i] * (mp[i] - 1))
/ 2;
else
ans += (( long long )mp[i]) * mp[j];
}
}
}
return ans;
}
int main()
{
int arr[] = { 6, 4, 2, 3 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << countPairs(arr, n);
return 0;
}
|
Java
import java.util.*;
class Main {
public static long countPairs( int [] arr, int n)
{
long ans = 0 , mx = 0 ;
Map<Integer, Integer> mp = new HashMap<>();
for ( int ai : arr) {
mp.put(ai, mp.getOrDefault(ai, 0 ) + 1 );
mx = Math.max(mx, ai);
}
for ( int i = 0 ; i <= mx; ++i) {
if (!mp.containsKey(i))
continue ;
for ( int j = i; j <= mx; ++j) {
if (!mp.containsKey(j))
continue ;
if (Long.bitCount(i & j) == 1 ) {
if (i == j)
ans += (( long )mp.get(i)
* (mp.get(i) - 1 ))
/ 2 ;
else
ans += (( long )mp.get(i))
* mp.get(j);
}
}
}
return ans;
}
public static void main(String[] args)
{
int arr[] = new int [] { 6 , 4 , 2 , 3 };
int n = arr.length;
System.out.print(countPairs(arr, n));
}
}
|
Python3
from typing import List
from collections import defaultdict
def countPairs(arr: List [ int ], n: int ) - > int :
ans, mx = 0 , 0
mp = defaultdict( int )
for ai in arr:
mp[ai] + = 1
mx = max (mx, ai)
for i in range (mx + 1 ):
if i not in mp:
continue
for j in range (i, mx + 1 ):
if j not in mp:
continue
if bin (i & j).count( '1' ) = = 1 :
if i = = j:
ans + = (mp[i] * (mp[i] - 1 )) / / 2
else :
ans + = mp[i] * mp[j]
return ans
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;
Dictionary< int , int > mp = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
int ai = arr[i];
if (mp.ContainsKey(ai))
mp[ai]++;
else
mp.Add(ai, 1);
mx = Math.Max(mx, ( long )ai);
}
for ( int i = 0; i <= mx; ++i)
{
if (!mp.ContainsKey(i))
continue ;
for ( int j = i; j <= mx; ++j)
{
if (!mp.ContainsKey(j))
continue ;
if (CountSetBits(i & j) == 1)
{
if (i == j)
ans += (( long )mp[i] * (mp[i] - 1)) / 2;
else
ans += (( long )mp[i]) * mp[j];
}
}
}
return ans;
}
public static int CountSetBits( int num)
{
int count = 0;
while (num > 0)
{
count += num & 1;
num >>= 1;
}
return count;
}
public static void Main( string [] args)
{
int [] arr = { 6, 4, 2, 3 };
int n = arr.Length;
Console.WriteLine(CountPairs(arr, n));
}
}
|
Javascript
function countPairs(arr) {
let ans = 0;
let mx = 0;
const mp = new Map();
for (let i = 0; i < arr.length; i++) {
const ai = arr[i];
mp.set(ai, (mp.get(ai) || 0) + 1);
mx = Math.max(mx, ai);
}
for (let i = 0; i <= mx; i++) {
if (!mp.has(i)) {
continue ;
}
for (let j = i; j <= mx; j++) {
if (!mp.has(j)) {
continue ;
}
if (countSetBits(i & j) === 1) {
if (i === j) {
ans += (mp.get(i) * (mp.get(i) - 1)) / 2;
}
else {
ans += mp.get(i) * mp.get(j);
}
}
}
}
return ans;
}
function countSetBits(num) {
let count = 0;
while (num > 0) {
count += num & 1;
num >>= 1;
}
return count;
}
const arr = [6, 4, 2, 3];
console.log(countPairs(arr));
|
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)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
24 Aug, 2023
Like Article
Save Article