Count all pairs of an array which differ in K bits
Given an array of size n and integer k, count all pairs in array which differ in exactly K bits of binary representation of both the numbers.
The input arrays have elements with small values and possibly many repetitions.
Examples:
Input: arr[] = {2, 4, 1, 3, 1}
k = 2
Output: 5
Explanation:
There are only 4 pairs which differs in
exactly 2 bits of binary representation:
(2, 4), (1, 2) [Two times] and (4, 1)
[Two times]
Input : arr[] = {2, 1, 2, 1}
k = 2
Output : 4
We strongly recommend that you click here and practice it, before moving on to the solution.
Naive Approach
A brute force is to run the two loops one inside the another and select the pairs one by one and take a XOR of both elements. The result of XORed value contains a set bits which are differ in both the elements. Now we just need to count total set bits so that we compare it with value K.
Below is the implementation of above approach:
C++
#include<bits/stdc++.h>
using namespace std;
int bitCount( int n)
{
int count = 0;
while (n)
{
if (n & 1)
++count;
n >>= 1;
}
return count;
}
long long countPairsWithKDiff( int arr[], int n, int k)
{
long long ans = 0;
for ( int i = 0; i < n-1; ++i)
{
for ( int j = i + 1; j < n; ++j)
{
int xoredNum = arr[i] ^ arr[j];
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
int main()
{
int k = 2;
int arr[] = {2, 4, 1, 3, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "Total pairs for k = " << k << " are "
<< countPairsWithKDiff(arr, n, k) << "\n" ;
return 0;
}
|
Java
import java.io.*;
class GFG {
static int bitCount( int n)
{
int count = 0 ;
while (n> 0 )
{
if ((n & 1 )> 0 )
++count;
n >>= 1 ;
}
return count;
}
static long countPairsWithKDiff( int arr[], int n, int k)
{
long ans = 0 ;
for ( int i = 0 ; i < n- 1 ; ++i)
{
for ( int j = i + 1 ; j < n; ++j)
{
int xoredNum = arr[i] ^ arr[j];
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
public static void main (String[] args) {
int k = 2 ;
int arr[] = { 2 , 4 , 1 , 3 , 1 };
int n =arr.length;
System.out.println( "Total pairs for k = " + k + " are "
+ countPairsWithKDiff(arr, n, k) + "\n" );
}
}
|
Python3
def bitCount(n):
count = 0
while (n):
if (n & 1 ):
count + = 1
n >> = 1
return count
def countPairsWithKDiff(arr, n, k):
ans = 0
for i in range ( 0 , n - 1 , 1 ):
for j in range (i + 1 , n, 1 ):
xoredNum = arr[i] ^ arr[j]
if (k = = bitCount(xoredNum)):
ans + = 1
return ans
if __name__ = = '__main__' :
k = 2
arr = [ 2 , 4 , 1 , 3 , 1 ]
n = len (arr)
print ( "Total pairs for k =" , k, "are" ,
countPairsWithKDiff(arr, n, k))
|
C#
using System;
class GFG
{
static int bitCount( int n)
{
int count = 0;
while (n > 0)
{
if ((n & 1) > 0)
++count;
n >>= 1;
}
return count;
}
static long countPairsWithKDiff( int []arr,
int n, int k)
{
long ans = 0;
for ( int i = 0; i < n-1; ++i)
{
for ( int j = i + 1; j < n; ++j)
{
int xoredNum = arr[i] ^ arr[j];
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
public static void Main ()
{
int k = 2;
int []arr = {2, 4, 1, 3, 1};
int n = arr.Length;
Console.WriteLine( "Total pairs for k = " +
k + " are " +
countPairsWithKDiff(arr, n, k) + "\n" );
}
}
|
PHP
<?php
function bitCount( $n )
{
$count = 0;
while ( $n )
{
if ( $n & 1)
++ $count ;
$n >>= 1;
}
return $count ;
}
function countPairsWithKDiff( $arr , $n , $k )
{
$ans = 0;
for ( $i = 0; $i < $n -1; ++ $i )
{
for ( $j = $i + 1; $j < $n ; ++ $j )
{
$xoredNum = $arr [ $i ] ^ $arr [ $j ];
if ( $k == bitCount( $xoredNum ))
++ $ans ;
}
}
return $ans ;
}
$k = 2;
$arr = array (2, 4, 1, 3, 1);
$n = count ( $arr );
echo "Total pairs for k = " , $k , " are "
, countPairsWithKDiff( $arr , $n , $k ) , "\n" ;
?>
|
Javascript
<script>
function bitCount(n)
{
let count = 0;
while (n>0)
{
if ((n & 1)>0)
++count;
n >>= 1;
}
return count;
}
function countPairsWithKDiff(arr, n, k)
{
let ans = 0;
for (let i = 0; i < n-1; ++i)
{
for (let j = i + 1; j < n; ++j)
{
let xoredNum = arr[i] ^ arr[j];
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
let k = 2;
let arr = [2, 4, 1, 3, 1];
let n = arr.length;
document.write( "Total pairs for k = " + k + " are "
+ countPairsWithKDiff(arr, n, k) + "\n" );
</script>
|
Output:
Total pairs for k = 2 are 5
Time complexity: O(N2 * log MAX) where MAX is maximum element in input array.
Auxiliary space: O(1)
Efficient approach
This approach is efficient for the cases when input array has small elements and possibly many repetitions. The idea is to iterate from 0 to max(arr[i]) and for every pair(i, j) check the number of set bits in (i ^ j) and compare this with K. We can use inbuilt function of gcc( __builtin_popcount ) or precompute such array to make the check faster. If number of ones in i ^ j is equals to K then we will add the total count of both i and j.
C++
#include<bits/stdc++.h>
using namespace std;
long long kBitDifferencePairs( int arr[], int n, int k)
{
int MAX = *max_element(arr, arr+n);
long long count[MAX+1];
memset (count, 0, sizeof (count));
for ( int i=0; i < n; ++i)
++count[arr[i]];
long long ans = 0;
if (k == 0)
{
for ( int i = 0; i <= MAX; ++i)
ans += (count[i] * (count[i] - 1)) / 2;
return ans;
}
for ( int i = 0; i <= MAX; ++i)
{
if (!count[i])
continue ;
for ( int j = i + 1; j <= MAX; ++j)
{
if ( __builtin_popcount(i ^ j) == k)
ans += count[i] * count[j];
}
}
return ans;
}
int main()
{
int k = 2;
int arr[] = {2, 4, 1, 3, 1};
int n = sizeof (arr)/ sizeof (arr[0]);
cout << "Total pairs for k = " << k << " are = "
<< kBitDifferencePairs(arr, n, k) << "\n" ;
k = 3;
cout << "Total pairs for k = " << k << " are = "
<< kBitDifferencePairs(arr, n, k) ;
return 0;
}
|
Java
import java.util.*;
class GFG
{
static long kBitDifferencePairs( int arr[],
int n, int k)
{
int MAX = Arrays.stream(arr).max().getAsInt();
long []count = new long [MAX + 1 ];
Arrays.fill(count, 0 );
for ( int i = 0 ; i < n; ++i)
++count[arr[i]];
long ans = 0 ;
if (k == 0 )
{
for ( int i = 0 ; i <= MAX; ++i)
ans += (count[i] * (count[i] - 1 )) / 2 ;
return ans;
}
for ( int i = 0 ; i <= MAX; ++i)
{
if (count[i] == 0 )
continue ;
for ( int j = i + 1 ; j <= MAX; ++j)
{
if ( Integer.bitCount(i ^ j) == k)
ans += count[i] * count[j];
}
}
return ans;
}
public static void main(String[] args)
{
int k = 2 ;
int arr[] = { 2 , 4 , 1 , 3 , 1 };
int n = arr.length;
System.out.println( "Total pairs for k = " +
k + " are = " +
kBitDifferencePairs(arr, n, k));
k = 3 ;
System.out.println( "Total pairs for k = " +
k + " are = " +
kBitDifferencePairs(arr, n, k));
}
}
|
Python3
def kBitDifferencePairs(arr, n, k):
MAX = max (arr)
count = [ 0 for i in range ( MAX + 1 )]
for i in range (n):
count[arr[i]] + = 1
ans = 0
if (k = = 0 ):
for i in range ( MAX + 1 ):
ans + = (count[i] * (count[i] - 1 )) / / 2
return ans
for i in range ( MAX + 1 ):
if (count[i] = = 0 ):
continue
for j in range (i + 1 , MAX + 1 ):
if ( bin (i ^ j).count( '1' ) = = k):
ans + = count[i] * count[j]
return ans
k = 2
arr = [ 2 , 4 , 1 , 3 , 1 ]
n = len (arr)
print ( "Total pairs for k =" , k, "are" ,
kBitDifferencePairs(arr, n, k))
k = 3
print ( "Total pairs for k =" , k, "are" ,
kBitDifferencePairs(arr, n, k))
|
C#
using System;
using System.Linq;
class GFG
{
static long kBitDifferencePairs( int []arr,
int n, int k)
{
int MAX = arr.Max();
long []count = new long [MAX + 1];
for ( int i = 0; i < n; ++i)
++count[arr[i]];
long ans = 0;
if (k == 0)
{
for ( int i = 0; i <= MAX; ++i)
ans += (count[i] *
(count[i] - 1)) / 2;
return ans;
}
for ( int i = 0; i <= MAX; ++i)
{
if (count[i] == 0)
continue ;
for ( int j = i + 1; j <= MAX; ++j)
{
if (BitCount(i ^ j) == k)
ans += count[i] * count[j];
}
}
return ans;
}
static int BitCount( int n)
{
int count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
public static void Main(String[] args)
{
int k = 2;
int []arr = {2, 4, 1, 3, 1};
int n = arr.Length;
Console.WriteLine( "Total pairs for k = " +
k + " are = " +
kBitDifferencePairs(arr, n, k));
k = 3;
Console.WriteLine( "Total pairs for k = " +
k + " are = " +
kBitDifferencePairs(arr, n, k));
}
}
|
Javascript
<script>
function kBitDifferencePairs(arr, n, k)
{
let MAX = Math.max(...arr);
let count = new Array(MAX+1).fill(0);
for (let i=0; i < n; ++i)
++count[arr[i]];
let ans = 0;
if (k == 0)
{
for (let i = 0; i <= MAX; ++i)
ans += parseInt((count[i] *
(count[i] - 1)) / 2);
return ans;
}
for (let i = 0; i <= MAX; ++i)
{
if (!count[i])
continue ;
for (let j = i + 1; j <= MAX; ++j)
{
if ( BitCount(i ^ j) == k)
ans += count[i] * count[j];
}
}
return ans;
}
function BitCount(n)
{
let count = 0;
while (n > 0)
{
count += n & 1;
n >>= 1;
}
return count;
}
let k = 2;
let arr = [2, 4, 1, 3, 1];
let n = arr.length;
document.write( "Total pairs for k = " + k + " are = "
+ kBitDifferencePairs(arr, n, k) + "<br>" );
k = 3;
document.write( "Total pairs for k = " + k + " are = "
+ kBitDifferencePairs(arr, n, k) + "<br>" );
</script>
|
Output:
Total pairs for k = 2 are = 5
Time complexity: O(MAX2) where MAX is maximum element in input array.
Auxiliary space: O(MAX)
Last Updated :
13 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...