Open In App

Count pairs in an array such that both elements has equal set bits

Last Updated : 03 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr [] of size N with unique elements, the task is to count the total number of pairs of elements that have equal set bits count.

Examples: 

Input: arr[] = {2, 5, 8, 1, 3} 
Output:
Set bits counts for {2, 5, 8, 1, 3} are {1, 2, 1, 1, 2} 
All pairs with same set bits count are {2, 8}, {2, 1}, {5, 3}, {8, 1}

Input: arr[] = {1, 11, 7, 3} 
Output:
Only possible pair is {11, 7} 

Approach: 

  • Traverse the array from left to right and count total number of set bits of each integer.
  • Use a map to store the number of elements with same count of set bits with set bits as key, and count as value.
  • Then iterator through map elements, and calculate how many two-element pairs can be formed from n elements (for each element of the map) i.e. (n * (n-1)) / 2.
  • The final result will be the sum of output from the previous step for every element of the map.

Below is the implementation of the above approach: 

C++




// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to count all pairs
// with equal set bits count
int totalPairs(int arr[], int n)
{
    // map to store count of elements
    // with equal number of set bits
    map<int, int> m;
    for (int i = 0; i < n; i++) {
 
        // inbuilt function that returns the
        // count of set bits of the number
        m[__builtin_popcount(arr[i])]++;
    }
 
    map<int, int>::iterator it;
    int result = 0;
    for (it = m.begin(); it != m.end(); it++) {
 
        // there can be (n*(n-1)/2) unique two-
        // element pairs to choose from n elements
        result
            += (*it).second * ((*it).second - 1) / 2;
    }
 
    return result;
}
 
// Driver code
int main()
{
    int arr[] = { 7, 5, 3, 9, 1, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << totalPairs(arr, n);
 
    return 0;
}


Java




import java.util.*;
 
class GFG {
     
    /* Function to get no of set 
    bits in binary representation 
    of passed binary no. */
    static int countSetBits(int n)
    {
        int count = 0;
        while (n > 0)
        {
            n &= (n - 1) ;
            count++;
        }
        return count;
    }
     
    // Function to count all pairs
    // with equal set bits count
    static int totalPairs(int arr[], int n)
    {
        // map to store count of elements
        // with equal number of set bits
        HashMap<Integer, Integer> m = new HashMap<>();
        for (int i = 0; i < n; i++) {
     
            // function that returns the
            // count of set bits of the number
            int count = countSetBits(arr[i]);
            if(m.containsKey(count))
                m.put(count, m.get(count) + 1);
            else
                m.put(count, 1);
        }
     
        int result = 0;
        for (Map.Entry<Integer, Integer> entry : m.entrySet()) {
            int value = entry.getValue();
             
            // there can be (n*(n-1)/2) unique two-
            // element pairs to choose from n elements
            result += ((value * (value -1)) / 2);
        }
     
        return result;
    }
     
    public static void main (String[] args) {
        int arr[] = { 7, 5, 3, 9, 1, 2 };
        int n = arr.length;
        System.out.println(totalPairs(arr, n));
    }
}


Python3




# Python3 implementation of the above approach
 
# Function to count all pairs
# with equal set bits count
def totalPairs(arr, n):
     
    # dictionary to store count of elements
    # with equal number of set bits
    m = dict()
 
    for i in range(n):
 
        # inbuilt function that returns the
        # count of set bits of the number
        x = bin(arr[i]).count('1')
 
        m[x] = m.get(x, 0) + 1;
 
    result = 0
    for it in m:
 
        # there can be (n*(n-1)/2) unique two-
        # element pairs to choose from n elements
        result+= (m[it] * (m[it] - 1)) // 2
     
    return result
 
# Driver code
arr = [7, 5, 3, 9, 1, 2]
n = len(arr)
 
print(totalPairs(arr, n))
 
# This code is contributed by mohit kumar


C#




// C# program to rearrange a string so that all same
// characters become atleast d distance away
using System;
using System.Collections.Generic;
 
class GFG
{
     
    /* Function to get no of set
    bits in binary representation
    of passed binary no. */
    static int countSetBits(int n)
    {
        int count = 0;
        while (n > 0)
        {
            n &= (n - 1) ;
            count++;
        }
        return count;
    }
     
    // Function to count all pairs
    // with equal set bits count
    static int totalPairs(int []arr, int n)
    {
        // map to store count of elements
        // with equal number of set bits
        Dictionary<int,int> mp = new Dictionary<int,int>();
        for (int i = 0 ; i < n; i++)
        {
            // function that returns the
            // count of set bits of the number
            int count = countSetBits(arr[i]);
            if(mp.ContainsKey(count))
            {
                var val = mp[count];
                mp.Remove(count);
                mp.Add(count, val + 1);
            }
            else
            {
                mp.Add(count, 1);
            }
        }
     
        int result = 0;
        foreach(KeyValuePair<int, int> entry in mp){
            int values = entry.Value;
             
            // there can be (n*(n-1)/2) unique two-
            // element pairs to choose from n elements
            result += ((values * (values -1)) / 2);
        }
     
        return result;
    }
     
    // Driver code
    public static void Main (String[] args)
    {
        int []arr = { 7, 5, 3, 9, 1, 2 };
        int n = arr.Length;
        Console.WriteLine(totalPairs(arr, n));
    }
}
 
// This code is contributed by Princi Singh


Javascript




<script>
 
// Javascript implementation of above approach
 
 /* Function to get no of set
bits in binary representation
of passed binary no. */
function countSetBits(n)
{
    var count = 0;
    while (n > 0)
    {
        n &= (n - 1) ;
        count++;
    }
    return count;
}
 
// Function to count all pairs
// with equal set bits count
function totalPairs(arr, n)
{
    // map to store count of elements
    // with equal number of set bits
    var m = new Map();
    for (var i = 0; i < n; i++) {
 
        // inbuilt function that returns the
        // count of set bits of the number
        if(m.has(arr[i]))
        {
            m.set(countSetBits(arr[i]), m.get(countSetBits(arr[i]))+1);
        }
        else{
            m.set(countSetBits(arr[i]), 1);
        }
         
    }
 
    var result = 0;
    m.forEach((value, key) => {
        // there can be (n*(n-1)/2) unique two-
        // element pairs to choose from n elements
        result += parseInt(key * (key - 1) / 2);
    });
     
    return result;
}
 
// Driver code
var arr = [7, 5, 3, 9, 1, 2 ];
var n = arr.length;
document.write( totalPairs(arr, n));
 
</script>


Output

4

Time Complexity: O(n log n), where n is the number of elements in given array
Auxiliary Space:  O(n)



Similar Reads

Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X &amp; Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X &amp; Y) = M, where ⊕ denotes the Bitwise XOR and &amp; denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Count pairs (A, B) such that A has X and B has Y number of set bits and A+B = C
Given two numbers x, y which denotes the number of set bits. Also given is a number C. The task is to print the number of ways in which we can form two numbers A and B such that A has x number of set bits and B has y number of set bits and A+B = C.Examples: Input: X = 1, Y = 1, C = 3 Output: 2 So two possible ways are (A = 2 and B = 1) and (A = 1 a
30 min read
Count of Pairs in given Array having both even or both odd or sum as K
Given an array arr[] of distinct integers of size N and an integer K, The task is to find the total no of possible pairs in the array such that, either both are even or both are odd or the sum of the pair is K Note: No element is part of more than one pair. Examples: Input: N = 6, K = 7, arr[] = {1, 2, 3, 4, 5, 6}Output: 3Explanation: Possible pair
7 min read
Check if every index i has an index j such that sum of elements in both directions are equal
Given a circular array of size N. The task is to check if, for every index, i starting from 0 to N-1, there exists an index j that is not equal to i such that the sum of all the numbers in the clockwise direction from i to j is equal to the sum of all numbers in the anticlockwise direction from i to j. Examples: Input: a[] = {1, 4, 1, 4} Output: Ye
6 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n &gt; 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Check if array can be sorted by swapping pairs with GCD of set bits count equal to that of the smallest array element
Given an array arr[] consisting of N integers, the task is to check if it is possible to sort the array using the following swap operations: Swapping of two numbers is valid only if the Greatest Common Divisor of count of set bits of the two numbers is equal to the number of set bits in the smallest element of the array. If it is possible to sort t
9 min read
Count pairs of elements such that number of set bits in their AND is B[i]
Given two arrays A[] and B[] of N elements each. The task is to find the number of index pairs (i, j) such that i ? j and F(A[i] &amp; A[j]) = B[j] where F(X) is the count of set bits in the binary representation of X.Examples: Input: A[] = {2, 3, 1, 4, 5}, B[] = {2, 2, 1, 4, 2} Output: 4 All possible pairs are (3, 3), (3, 1), (1, 1) and (5, 5)Inpu
5 min read
Count pairs of elements such that number of set bits in their OR is B[i]
Given two arrays A[] and B[] of N elements each. The task is to find the number of index pairs (i, j) such that i ? j and F(A[i] | A[j]) = B[j] where F(X) is the count of set bits in the binary representation of X.Examples Input: A[] = {5, 3, 2, 4, 6, 1}, B[] = {2, 2, 1, 4, 2, 3} Output: 7 All possible pairs are (5, 5), (3, 3), (2, 2), (2, 6), (4,
5 min read
Minimize operations to make both arrays equal by decrementing a value from either or both
Given two arrays A[] and B[] having N integers, the task is to find the minimum operations required to make all the elements of both the array equal where at each operation, the following can be done: Decrement the value of A[i] by 1 where i lies in the range [0, N).Decrement the value of B[i] by 1 where i lies in the range [0, N).Decrement the val
8 min read
Count pairs in Array such that their bitwise XOR has Kth right bit set
Given an array arr[] of size N and an integer K, the task is to find the number of pairs in the array such that the Kth bit from the right of their bitwise XOR is set. Examples: Input: arr[] = {3, 13, 2, 9}, N = 4, K = 3Output: 4Explanation: The pairs that have the kth bit set in bitwise xor value are {3, 13}, {3, 9}, {2, 13}, {2, 9} Input: arr[] =
11 min read
Article Tags :
Practice Tags :