VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-all-pairs-of-an-array-which-differ-in-k-bits/

⇱ Count all pairs of an array which differ in K bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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:
 

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. 
 

Output:

Total pairs for k = 2 are = 5


Time complexity: O(MAX2) where MAX is maximum element in input array. 
Auxiliary space: O(MAX)
 

Comment
Article Tags: