Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Number of Good Pairs - Count of index pairs with equal values in an array
Next article icon

Count of pairs in an Array with same number of set bits

Last Updated : 15 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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 with 3 set bits: 7 
Hence, {1, 2}, {1, 4}, {1, 8}, {2, 4}, {2, 8}, {4, 8}, {3, 5}, {3, 6}, and {5, 6} are the possible such pairs.

Input: N = 12, arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} 
Output: 22 

Approach:  

  • Precompute and store the set bits for all numbers up to the maximum element of the array in bitscount[]. For all powers of 2, store 1 at their respective index. After that, compute the set bits count for the remaining elements by the relation:

bitscount[i] = bitscount[previous power of 2] + bitscount[i - previous power of 2]  

  • Store the frequency of set bits in the array elements in a Map.
  • Add the number of possible pairs for every set bit count. If X elements have the same number of set bits, the number of possible pairs among them is X * (X - 1) / 2.
  • Print the total count of such pairs.

The below code is the implementation of the above approach:

C++14
// C++ Program to count // possible number of pairs // of elements with same // number of set bits.  #include <bits/stdc++.h> using namespace std;  // Function to return the // count of Pairs int countPairs(int arr[], int N) {     // Get the maximum element     int maxm = *max_element(arr, arr + N);      int i, k;     // Array to store count of bits     // of all elements upto maxm     int bitscount[maxm + 1] = { 0 };      // Store the set bits     // for powers of 2     for (i = 1; i <= maxm; i *= 2)         bitscount[i] = 1;     // Compute the set bits for     // the remaining elements     for (i = 1; i <= maxm; i++) {         if (bitscount[i] == 1)             k = i;         if (bitscount[i] == 0) {             bitscount[i]                 = bitscount[k]                   + bitscount[i - k];         }     }      // Store the frequency     // of respective counts     // of set bits     map<int, int> setbits;     for (int i = 0; i < N; i++) {         setbits[bitscount[arr[i]]]++;     }      int ans = 0;     for (auto it : setbits) {         ans += it.second                * (it.second - 1) / 2;     }      return ans; }  int main() {     int N = 12;     int arr[] = { 1, 2, 3, 4, 5, 6, 7,                   8, 9, 10, 11, 12 };      cout << countPairs(arr, N);      return 0; } 
Java
// Java program to count possible  // number of pairs of elements  // with same number of set bits import java.util.*; import java.lang.*;  class GFG{      // Function to return the  // count of Pairs  static int countPairs(int []arr, int N)  {           // Get the maximum element      int maxm = arr[0];             for(int j = 1; j < N; j++)      {          if (maxm < arr[j])          {              maxm = arr[j];          }      }         int i, k = 0;             // Array to store count of bits      // of all elements upto maxm      int[] bitscount = new int[maxm + 1];      Arrays.fill(bitscount, 0);         // Store the set bits      // for powers of 2      for(i = 1; i <= maxm; i *= 2)          bitscount[i] = 1;                 // Compute the set bits for      // the remaining elements      for(i = 1; i <= maxm; i++)      {          if (bitscount[i] == 1)              k = i;          if (bitscount[i] == 0)          {              bitscount[i] = bitscount[k] +                              bitscount[i - k];          }     }         // Store the frequency      // of respective counts      // of set bits      Map<Integer, Integer> setbits = new HashMap<>();             for(int j = 0; j < N; j++)       {          setbits.put(bitscount[arr[j]],         setbits.getOrDefault(             bitscount[arr[j]], 0) + 1);      }         int ans = 0;         for(int it : setbits.values())     {          ans += it * (it - 1) / 2;             }      return ans;  }   // Driver code public static void main(String[] args) {     int N = 12;      int []arr = { 1, 2, 3, 4, 5, 6, 7,                    8, 9, 10, 11, 12 };           System.out.println(countPairs(arr, N));  } }  // This code is contributed by offbeat 
Python3
# Python3 program to count possible number # of pairs of elements with same number # of set bits.   # Function to return the # count of Pairs def countPairs(arr, N):          # Get the maximum element     maxm = max(arr)     i = 0     k = 0          # Array to store count of bits     # of all elements upto maxm     bitscount = [0 for i in range(maxm + 1)]          i = 1          # Store the set bits     # for powers of 2     while i <= maxm:         bitscount[i] = 1         i *= 2              # Compute the set bits for     # the remaining elements     for i in range(1, maxm + 1):         if (bitscount[i] == 1):             k = i         if (bitscount[i] == 0):             bitscount[i] = (bitscount[k] +                              bitscount[i - k])       # Store the frequency     # of respective counts     # of set bits     setbits = dict()          for i in range(N):         if bitscount[arr[i]] in setbits:             setbits[bitscount[arr[i]]] += 1         else:             setbits[bitscount[arr[i]]] = 1       ans = 0          for it in setbits.values():         ans += it * (it - 1) // 2       return ans   # Driver Code if __name__=='__main__':          N = 12     arr = [ 1, 2, 3, 4, 5, 6, 7,             8, 9, 10, 11, 12 ]       print(countPairs(arr, N))   # This code is contributed by pratham76 
C#
// C# program to count // possible number of pairs // of elements with same // number of set bits. using System;  using System.Collections;  using System.Collections.Generic;  using System.Text;   class GFG{      // Function to return the // count of Pairs static int countPairs(int []arr, int N) {          // Get the maximum element     int maxm = -int.MaxValue;          for(int j = 0; j < N; j++)     {         if (maxm < arr[j])         {             maxm = arr[j];         }     }      int i, k = 0;          // Array to store count of bits     // of all elements upto maxm     int []bitscount = new int[maxm + 1];     Array.Fill(bitscount, 0);      // Store the set bits     // for powers of 2     for(i = 1; i <= maxm; i *= 2)         bitscount[i] = 1;              // Compute the set bits for     // the remaining elements     for(i = 1; i <= maxm; i++)     {         if (bitscount[i] == 1)             k = i;         if (bitscount[i] == 0)         {             bitscount[i] = bitscount[k] +                             bitscount[i - k];         }     }      // Store the frequency     // of respective counts     // of set bits     Dictionary<int,                 int> setbits = new Dictionary<int,                                              int>();          for(int j = 0; j < N; j++)      {         if (setbits.ContainsKey(bitscount[arr[j]]))         {             setbits[bitscount[arr[j]]]++;          }         else         {             setbits[bitscount[arr[j]]] = 1;         }     }      int ans = 0;      foreach(KeyValuePair<int, int> it in setbits)      {         ans += it.Value * (it.Value - 1) / 2;     }     return ans; }      // Driver Code public static void Main(string[] args) {     int N = 12;     int []arr = { 1, 2, 3, 4, 5, 6, 7,                   8, 9, 10, 11, 12 };      Console.Write(countPairs(arr, N)); } }  // This code is contributed by rutvik_56 
JavaScript
<script>  // Javascript Program to count // possible number of pairs // of elements with same // number of set bits.  // Function to return the // count of Pairs function countPairs(arr, N) {     // Get the maximum element     var maxm = arr.reduce((a,b)=>Math.max(a,b));      var i, k;     // Array to store count of bits     // of all elements upto maxm     var bitscount = Array(maxm+1).fill(0);      // Store the set bits     // for powers of 2     for (i = 1; i <= maxm; i *= 2)         bitscount[i] = 1;     // Compute the set bits for     // the remaining elements     for (i = 1; i <= maxm; i++) {         if (bitscount[i] == 1)             k = i;         if (bitscount[i] == 0) {             bitscount[i]                 = bitscount[k]                   + bitscount[i - k];         }     }      // Store the frequency     // of respective counts     // of set bits     var setbits = new Map();     for (var i = 0; i < N; i++) {          if(setbits.has(bitscount[arr[i]]))             setbits.set(bitscount[arr[i]],               setbits.get(bitscount[arr[i]])+1)         else             setbits.set(bitscount[arr[i]], 1)     }      var ans = 0;      setbits.forEach((value, key) => {         ans += value                * (value - 1) / 2;     });      return ans; }  var N = 12; var arr = [1, 2, 3, 4, 5, 6, 7,               8, 9, 10, 11, 12]; document.write( countPairs(arr, N));   </script>  

Output: 
22

 

Next Article
Number of Good Pairs - Count of index pairs with equal values in an array

N

noob_coder123
Improve
Article Tags :
  • Bit Magic
  • Dynamic Programming
  • DSA
  • Arrays
  • setBitCount
Practice Tags :
  • Arrays
  • Bit Magic
  • Dynamic Programming

Similar Reads

  • Program to count number of set bits in an (big) array
    Given an integer array of length N (an arbitrarily large number). How to count number of set bits in the array?The simple approach would be, create an efficient method to count set bits in a word (most prominent size, usually equal to bit length of processor), and add bits from individual elements o
    12 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
  • Number of Good Pairs - Count of index pairs with equal values in an array
    Given an array of n elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i < j Examples : Input: arr = [5, 2, 3, 5, 5, 3]Output: 4Explanation: There are 4 good pairs (0, 3), (0, 4), (3, 4), (2, 5) Input: arr = [1, 1, 1, 1]Output: 6Explanation: All 6 pair
    7 min read
  • Find Unique pair in an array with pairs of numbers
    Given an array where every element appears twice except a pair (two elements). Find the elements of this unique pair.Examples: Input : 6, 1, 3, 5, 1, 3, 7, 6 Output : 5 7 All elements appear twice except 5 and 7 Input : 1 3 4 1 Output : 3 4Recommended PracticeFind Unique pair in an array with pairs
    8 min read
  • Count pairs with Bitwise AND as ODD number
    Given an array of N integers. The task is to find the number of pairs (i, j) such that A[i] & A[j] is odd.Examples: Input: N = 4 A[] = { 5, 1, 3, 2 } Output: 3 Since pair of A[] = ( 5, 1 ), ( 5, 3 ), ( 5, 2 ), ( 1, 3 ), ( 1, 2 ), ( 3, 2 ) 5 AND 1 = 1, 5 AND 3 = 1, 5 AND 2 = 0, 1 AND 3 = 1, 1 AND
    9 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
  • Maximum number of contiguous array elements with same number of set bits
    Given an array with n elements. The task is to find the maximum number of contiguous array elements which have the same number of set bits. Examples: Input : arr[] = {14, 1, 2, 32, 12, 10} Output : 3 Elements 1, 2, 32 have same number of set bits and are contiguous. Input : arr[] = {1, 6, 9, 15, 8}
    6 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] & 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 possib
    5 min read
  • Count Pairs with Specific Bit Set in two Arrays
    Given two arrays A1 and A2 of size N, and Q queries, each query contains 5 numbers k, l1, r1, l2, r2. For each query, we have to return the total number of pairs (i, j), such that l1 <= i <= r1, l2 <= j <= r2, and A1[i]^A2[j] have its kth bit from the end set. 1-based indexing must be fo
    12 min read
  • Count pairs with Bitwise-AND as even number
    Given an array of [Tex]N [/Tex]integers. The task is to find the number of pairs (i, j) such that A[i] & A[j] is even. Examples: Input: N = 4, A[] = { 5, 1, 3, 2 } Output: 3 Since pair of A[] are: ( 5, 1 ), ( 5, 3 ), ( 5, 2 ), ( 1, 3 ), ( 1, 2 ), ( 3, 2 ) 5 AND 1 = 1, 5 AND 3 = 1, 5 AND 2 = 0, 1
    13 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences