Count all pairs of an array which differ in K bits
Last Updated :
13 Sep, 2023
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++
// C++ program to count all pairs with bit difference
// as k
#include<bits/stdc++.h>
using namespace std;
// Utility function to count total ones in a number
int bitCount(int n)
{
int count = 0;
while (n)
{
if (n & 1)
++count;
n >>= 1;
}
return count;
}
// Function to count pairs of K different bits
long long countPairsWithKDiff(int arr[], int n, int k)
{
long long ans = 0; // initialize final answer
for (int i = 0; i < n-1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
int xoredNum = arr[i] ^ arr[j];
// Check for K differ bit
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
// Driver code
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
// Java program to count all pairs with bit difference
// as k
import java.io.*;
class GFG {
// Utility function to count total ones in a number
static int bitCount(int n)
{
int count = 0;
while (n>0)
{
if ((n & 1)>0)
++count;
n >>= 1;
}
return count;
}
// Function to count pairs of K different bits
static long countPairsWithKDiff(int arr[], int n, int k)
{
long ans = 0; // initialize final answer
for (int i = 0; i < n-1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
int xoredNum = arr[i] ^ arr[j];
// Check for K differ bit
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
// Driver code
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");
}
}
// This code is contributed by shs..
Python3
# Python 3 program to count all pairs
# with bit difference as k
# Utility function to count total
# ones in a number
def bitCount(n):
count = 0
while (n):
if (n & 1):
count += 1
n >>= 1
return count
# Function to count pairs of K different bits
def countPairsWithKDiff(arr, n, k):
ans = 0
# initialize final answer
for i in range(0, n - 1, 1):
for j in range(i + 1, n, 1):
xoredNum = arr[i] ^ arr[j]
# Check for K differ bit
if (k == bitCount(xoredNum)):
ans += 1
return ans
# Driver code
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))
# This code is contributed by
# Sanjit_Prasad
C#
// C# program to count all pairs
// with bit difference as k
using System;
class GFG
{
// Utility function to count
// total ones in a number
static int bitCount(int n)
{
int count = 0;
while (n > 0)
{
if ((n & 1) > 0)
++count;
n >>= 1;
}
return count;
}
// Function to count pairs of K different bits
static long countPairsWithKDiff(int []arr,
int n, int k)
{
long ans = 0; // initialize final answer
for (int i = 0; i < n-1; ++i)
{
for (int j = i + 1; j < n; ++j)
{
int xoredNum = arr[i] ^ arr[j];
// Check for K differ bit
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
// Driver code
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");
}
}
// This code is contributed by shs..
PHP
<?php
// PHP program to count all
// pairs with bit difference
// as k
// Utility function to count
// total ones in a number
function bitCount($n)
{
$count = 0;
while ($n)
{
if ($n & 1)
++$count;
$n >>= 1;
}
return $count;
}
// Function to count pairs
// of K different bits
function countPairsWithKDiff($arr, $n, $k)
{
// initialize final answer
$ans = 0;
for ($i = 0; $i < $n-1; ++$i)
{
for ($j = $i + 1; $j < $n; ++$j)
{
$xoredNum = $arr[$i] ^ $arr[$j];
// Check for K differ bit
if ($k == bitCount($xoredNum))
++$ans;
}
}
return $ans;
}
// Driver code
$k = 2;
$arr = array(2, 4, 1, 3, 1);
$n = count($arr);
echo "Total pairs for k = " , $k , " are "
, countPairsWithKDiff($arr, $n, $k) , "\n";
// This code is contributed by anuj_67.
?>
JavaScript
<script>
// JavaScript program to count all pairs with bit difference
// as k
// Utility function to count total ones in a number
function bitCount(n)
{
let count = 0;
while (n>0)
{
if ((n & 1)>0)
++count;
n >>= 1;
}
return count;
}
// Function to count pairs of K different bits
function countPairsWithKDiff(arr, n, k)
{
let ans = 0; // initialize final answer
for (let i = 0; i < n-1; ++i)
{
for (let j = i + 1; j < n; ++j)
{
let xoredNum = arr[i] ^ arr[j];
// Check for K differ bit
if (k == bitCount(xoredNum))
++ans;
}
}
return ans;
}
// Driver Code
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++
// Below is C++ approach of finding total k bit
// difference pairs
#include<bits/stdc++.h>
using namespace std;
// Function to calculate K bit different pairs in array
long long kBitDifferencePairs(int arr[], int n, int k)
{
// Get the maximum value among all array elements
int MAX = *max_element(arr, arr+n);
// Set the count array to 0, count[] stores the
// total frequency of array elements
long long count[MAX+1];
memset(count, 0, sizeof(count));
for (int i=0; i < n; ++i)
++count[arr[i]];
// Initialize result
long long ans = 0;
// For 0 bit answer will be total count of same number
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] is 0, skip the next loop as it
// will not contribute the answer
if (!count[i])
continue;
for (int j = i + 1; j <= MAX; ++j)
{
//Update answer if k differ bit found
if ( __builtin_popcount(i ^ j) == k)
ans += count[i] * count[j];
}
}
return ans;
}
// Driver code
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
// Below is Java approach of finding total k bit
// difference pairs
import java.util.*;
class GFG
{
// Function to calculate K bit
// different pairs in array
static long kBitDifferencePairs(int arr[],
int n, int k)
{
// Get the maximum value among all array elements
int MAX = Arrays.stream(arr).max().getAsInt();
// Set the count array to 0,
// count[] stores the total
// frequency of array elements
long []count = new long[MAX + 1];
Arrays.fill(count, 0);
for (int i = 0; i < n; ++i)
++count[arr[i]];
// Initialize result
long ans = 0;
// For 0 bit answer will be total
// count of same number
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] is 0, skip the next loop
// as it will not contribute the answer
if (count[i] == 0)
continue;
for (int j = i + 1; j <= MAX; ++j)
{
// Update answer if k differ bit found
if ( Integer.bitCount(i ^ j) == k)
ans += count[i] * count[j];
}
}
return ans;
}
// Driver code
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));
}
}
// This code is contributed by Rajput-Ji
Python3
# Below is Python3 approach of finding
# total k bit difference pairs
# Function to calculate K bit different
# pairs in array
def kBitDifferencePairs(arr, n, k):
# Get the maximum value among
# all array elements
MAX = max(arr)
# Set the count array to 0, count[] stores
# the total frequency of array elements
count = [0 for i in range(MAX + 1)]
for i in range(n):
count[arr[i]] += 1
# Initialize result
ans = 0
# For 0 bit answer will be total
# count of same number
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] is 0, skip the next loop
# as it will not contribute the answer
if (count[i] == 0):
continue
for j in range(i + 1, MAX + 1):
# Update answer if k differ bit found
if (bin(i ^ j).count('1') == k):
ans += count[i] * count[j]
return ans
# Driver code
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))
# This code is contributed by mohit kumar
C#
// Below is C# approach of finding
// total k bit difference pairs
using System;
using System.Linq;
class GFG
{
// Function to calculate K bit
// different pairs in array
static long kBitDifferencePairs(int []arr,
int n, int k)
{
// Get the maximum value among
// all array elements
int MAX = arr.Max();
// Set the count array to 0,
// count[] stores the total
// frequency of array elements
long []count = new long[MAX + 1];
for (int i = 0; i < n; ++i)
++count[arr[i]];
// Initialize result
long ans = 0;
// For 0 bit answer will be total
// count of same number
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] is 0, skip the next loop
// as it will not contribute the answer
if (count[i] == 0)
continue;
for (int j = i + 1; j <= MAX; ++j)
{
// Update answer if k differ bit found
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;
}
// Driver code
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));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Below is Javascript approach
// of finding total k bit
// difference pairs
// Function to calculate K bit
// different pairs in array
function kBitDifferencePairs(arr, n, k)
{
// Get the maximum value among
// all array elements
let MAX = Math.max(...arr);
// Set the count array to 0, count[] stores the
// total frequency of array elements
let count = new Array(MAX+1).fill(0);
for (let i=0; i < n; ++i)
++count[arr[i]];
// Initialize result
let ans = 0;
// For 0 bit answer will be total
// count of same number
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] is 0, skip
// the next loop as it
// will not contribute the answer
if (!count[i])
continue;
for (let j = i + 1; j <= MAX; ++j)
{
//Update answer if k differ bit found
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;
}
// Driver code
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)
Similar Reads
Count of pairs in an Array with same number of set bits
Given an array arr containing N integers, the task is to count the possible number of pairs of elements with the same number of set bits. Examples: Input: N = 8, arr[] = {1, 2, 3, 4, 5, 6, 7, 8} Output: 9 Explanation: Elements with 1 set bit: 1, 2, 4, 8 Elements with 2 set bits: 3, 5, 6 Elements wit
7 min read
Count pairs from given array with Bitwise OR equal to K
Given an array arr[] consisting of N positive integers and an integer K, the task is to count all pairs possible from the given array with Bitwise OR equal to K. Examples: Input: arr[] = {2, 38, 44, 29, 62}, K = 46Output: 2Explanation: Only the following two pairs are present in the array whose Bitw
5 min read
Count pairs in an array which have at least one digit common
Given an array of N numbers. Find out the number of pairs i and j such that i < j and Ai and Aj have at least one digit common (For e.g. (11, 19) have 1 digit common but (36, 48) have no digit common) Examples: Input: A[] = { 10, 12, 24 } Output: 2 Explanation: Two valid pairs are (10, 12) and (1
14 min read
Count pairs in an array whose absolute difference is divisible by K
Given an array arr[] and a positive integer K. The task is to count the total number of pairs in the array whose absolute difference is divisible by K. Examples: Input: arr[] = {1, 2, 3, 4}, K = 2 Output: 2 Explanation: Total 2 pairs exists in the array with absolute difference divisible by 2. The p
14 min read
Count pairs with bitwise XOR exceeding bitwise AND from a given array
Given an array, arr[] of size N, the task is to count the number of pairs from the given array such that the bitwise AND(&) of each pair is less than its bitwise XOR(^). Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 8Explanation: Pairs that satisfy the given conditions are: (1 & 2) < (
10 min read
Given two arrays count all pairs whose sum is an odd number
Given two arrays of N and M integers. The task is to find the number of unordered pairs formed of elements from both arrays in such a way that their sum is an odd number. Note: An element can only be one pair.Examples: Input: a[] = {9, 14, 6, 2, 11}, b[] = {8, 4, 7, 20} Output: 3 {9, 20}, {14, 7} an
7 min read
Count number of pairs of arrays (a, b) such that a[i] <= b[i]
Given two integers n and m, the task is to count the number of pairs of arrays (a, b) where both arrays have a length of m, contain integers between 1 and n (inclusive), and satisfy the conditions that each element in array a is less than or equal to the corresponding element in array b for all indi
9 min read
Count pairs from two arrays with difference exceeding K
Given two integer arrays arr[] and brr[] consisting of distinct elements of size N and M respectively and an integer K, the task is to find the count of pairs(arr[i], brr[j]) such that (brr[j] - arr[i]) > K. Examples: Input: arr[] = {5, 9, 1, 8}, brr[] {10, 12, 7, 4, 2, 3}, K = 3 Output: 6 Explan
9 min read
Count pairs in an array whose absolute difference is divisible by K | Using Map
Given an array, arr[] of N elements and an integer K, the task is to find the number of pairs (i, j) such that the absolute value of (arr[i] - arr[j]) is a multiple of K. Examples: Input: N = 4, K = 2, arr[] = {1, 2, 3, 4}Output: 2Explanation: Total 2 pairs exists in the array with absolute differen
7 min read
Count of pairs in Array whose product is divisible by K
Given an array A[] and positive integer K, the task is to count the total number of pairs in the array whose product is divisible by K. Examples : Input: A[] = [1, 2, 3, 4, 5], K = 2Output: 7Explanation: The 7 pairs of indices whose corresponding products are divisible by 2 are(0, 1), (0, 3), (1, 2)
9 min read