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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Minimum and Maximum sum of absolute differences of pairs
Next article icon

Sum of bit differences among all pairs

Last Updated : 05 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given an integer array of n integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y. 

For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last bits differ in two numbers). 

Examples :  

Input: arr[] = {1, 2}  Output: 4  All pairs in array are (1, 1), (1, 2)                         (2, 1), (2, 2)  Sum of bit differences = 0 + 2 +                           2 + 0                        = 4    Input:  arr[] = {1, 3, 5}  Output: 8  All pairs in array are (1, 1), (1, 3), (1, 5)                         (3, 1), (3, 3) (3, 5),                         (5, 1), (5, 3), (5, 5)  Sum of bit differences =  0 + 1 + 1 +                            1 + 0 + 2 +                            1 + 2 + 0                          = 8

Source: Google Interview Question

Recommended Problem
Sum of bit differences
Solve Problem

Naive Solution:

A Simple Solution is to run two loops to consider all pairs one by one. For every pair, count bit differences. Finally return sum of counts. Time complexity of this solution is O(n2). We are using bitset::count() which is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. 

C++




// C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std;
  
int sum_bit_diff(vector<int> a)
{
    int n = a.size();
    int ans = 0;
  
    for (int i = 0; i < n - 1; i++) {
        int count = 0;
  
        for (int j = i; j < n; j++) {
            // Bitwise and of pair (a[i], a[j])
            int x = a[i] & a[j];
            // Bitwise or of pair (a[i], a[j])
            int y = a[i] | a[j];
  
            bitset<32> b1(x);
            bitset<32> b2(y);
  
            // to count set bits in and of two numbers
            int r1 = b1.count();
            // to count set bits in or of two numbers
            int r2 = b2.count();
  
            // Absolute differences at individual bit positions of two
            // numbers is contributed by pair (a[i], a[j]) in count
            count = abs(r1 - r2);
  
            // each pair adds twice of contributed count
            // as both (a, b) and (b, a) are considered
            // two separate pairs.
            ans = ans + (2 * count);
        }
    }
    return ans;
}
  
int main()
{
  
    vector<int> nums{ 10, 5 };
    int ans = sum_bit_diff(nums);
  
    cout << ans;
}
 
 

Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
    
    static int sumBitDiff(int[] arr){
        int diff = 0;                                //hold the ans
            
          for(int i=0; i<arr.length; i++){
            for(int j=i; j<arr.length; j++){
                
              //XOR toggles the bits and will form a number that will have
              //set bits at the places where the numbers bits differ
              //eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
                
                 int xor = arr[i]^arr[j];
                  int count = countSetBits(xor);        //Integer.bitCount() can also be used
                    
                  //when i == j (same numbers) the xor would be 0, 
                  //thus our ans will remain unaffected as (2*0 = 0)
                  diff += 2*count;
            }
        }
        
          return diff;
    }
    
    //Kernighan algo
      static int countSetBits(int n){
        int count = 0;            // `count` stores the total bits set in `n`
   
        while (n != 0) {
            n = n & (n - 1);    // clear the least significant bit set
            count++;
        }
   
        return count;
    }
    
    public static void main (String[] args) {
        int[] arr = {5,10};
          int ans  = sumBitDiff(arr);
        System.out.println(ans);
    }
}
 
 

Python3




# Python3 program for the above approach
def sumBitDiff(arr):
    diff = 0    #hold the ans
        
    for i in range(len(arr)):
        for j in range(i, len(arr)):
                
        # XOR toggles the bits and will form a number that will have
        # set bits at the places where the numbers bits differ
        # eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2           
            xor = arr[i]^arr[j]
            count = countSetBits(xor)        #Integer.bitCount() can also be used
                    
            # when i == j (same numbers) the xor would be 0, 
            # thus our ans will remain unaffected as (2*0 = 0)
            diff += (2*count)
        
    return diff
      
# Kernighan algo
def countSetBits(n):
    count = 0            # `count` stores the total bits set in `n`
   
    while (n != 0) :
        n = n & (n - 1)    # clear the least significant bit set
        count += 1
          
    return count
      
# Driver code
if __name__ == "__main__":
      
    arr = [5,10]
    ans  = sumBitDiff(arr)
    print(ans)
  
    # This code is contributed by sanjoy_62.
 
 

C#




/*package whatever //do not write package name here */
  
using System;
  
public class GFG {
    
    static int sumBitDiff(int[] arr){
        int diff = 0;                                //hold the ans
            
          for(int i=0; i<arr.Length; i++){
            for(int j=i; j<arr.Length; j++){
                
              //XOR toggles the bits and will form a number that will have
              //set bits at the places where the numbers bits differ
              //eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
                
                 int xor = arr[i]^arr[j];
                  int count = countSetBits(xor);        //int.bitCount() can also be used
                    
                  //when i == j (same numbers) the xor would be 0, 
                  //thus our ans will remain unaffected as (2*0 = 0)
                  diff += 2*count;
            }
        }
        
          return diff;
    }
    
    //Kernighan algo
      static int countSetBits(int n){
        int count = 0;            // `count` stores the total bits set in `n`
   
        while (n != 0) {
            n = n & (n - 1);    // clear the least significant bit set
            count++;
        }
   
        return count;
    }
    
    public static void Main(String[] args) {
        int[] arr = {5,10};
          int ans  = sumBitDiff(arr);
        Console.WriteLine(ans);
    }
}
  
// This code contributed by umadevi9616 
 
 

Javascript




<script>
  
// javascript program for above approach
    function sumBitDiff(arr)
    {
        let diff = 0;                                
        // hold the ans
            
          for(let i = 0; i < arr.length; i++){
            for(let j = i; j < arr.length; j++){
                
              // XOR toggles the bits and will form a number that will have
              // set bits at the places where the numbers bits differ
              // eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
                
                 let xor = arr[i]^arr[j];
                  let count = countSetBits(xor);        
                  // Integer.bitCount() can also be used
                    
                  // when i == j (same numbers) the xor would be 0, 
                  // thus our ans will remain unaffected as (2*0 = 0)
                  diff += 2*count;
            }
        }
        
          return diff;
    }
    
    // Kernighan algo
      function countSetBits(n){
        let count = 0;            // `count` stores the total bits set in `n`
   
        while (n != 0) {
            n = n & (n - 1);    // clear the least significant bit set
            count++;
        }
   
        return count;
    }
  
  
// Driver code
    let arr = [5,10];
    let ans  = sumBitDiff(arr);
    document.write(ans);
      
    // This code is contributed by splevel62.
</script>
 
 
Output
8

Time Complexity: O(n2)
Auxiliary Space: O(1)

Efficient Solution :

An Efficient Solution can solve this problem in O(n) time using the fact that all numbers are represented using 32 bits (or some fixed number of bits). The idea is to count differences at individual bit positions. We traverse from 0 to 31 and count numbers with i’th bit set. Let this count be ‘count’. There would be “n-count” numbers with i’th bit not set. So count of differences at i’th bit would be “count * (n-count) * 2”, the reason for this formula is as every pair having one element which has set bit at i’th position and second element having unset bit at i’th position contributes exactly 1 to sum, therefore total permutation count will be count*(n-count) and multiply by 2 is due to one more repetition of all this type of pair as per given condition for making pair 1<=i, j<=N.

Below is implementation of above idea.  

C++




// C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std;
  
int sumBitDifferences(int arr[], int n)
{
    int ans = 0; // Initialize result
    // traverse over all bits
    for (int i = 0; i < 32; i++) {
        // count number of elements with i'th bit set
        int count = 0;
        for (int j = 0; j < n; j++)
            if ((arr[j] & (1 << i)))
                count++;
        // Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
    }
    return ans;
}
  
// Driver program
int main()
{
    int arr[] = { 1, 3, 5 };
    int n = sizeof arr / sizeof arr[0];
    cout << sumBitDifferences(arr, n) << endl;
    return 0;
}
  
// This code is contributed by Sania Kumari Gupta (kriSania804)
 
 

C




// C program to compute sum of pairwise bit differences
#include <stdio.h>
  
int sumBitDifferences(int arr[], int n)
{
    int ans = 0; // Initialize result
    // traverse over all bits
    for (int i = 0; i < 32; i++) {
        // count number of elements with i'th bit set
        int count = 0;
        for (int j = 0; j < n; j++)
            if ((arr[j] & (1 << i)))
                count++;
        // Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
    }
    return ans;
}
  
// Driver program
int main()
{
    int arr[] = { 1, 3, 5 };
    int n = sizeof arr / sizeof arr[0];
    printf("%d\n", sumBitDifferences(arr, n));
    return 0;
}
  
// This code is contributed by Sania Kumari Gupta (kriSania804)
 
 

Java




// Java program to compute sum of pairwise
// bit differences
  
import java.io.*;
class GFG {
    static int sumBitDifferences(int arr[], int n)
    {
        int ans = 0; // Initialize result
        // traverse over all bits
        for (int i = 0; i < 32; i++) {
            // count number of elements with i'th bit set
            int count = 0;
            for (int j = 0; j < n; j++)
                if ((arr[j] & (1 << i)) != 0)
                    count++;
            // Add "count * (n - count) * 2"
            // to the answer...(n - count = unset bit count)
            ans += (count * (n - count) * 2);
        }
        return ans;
    }
  
    // Driver program
    public static void main(String args[])
    {
        int arr[] = { 1, 3, 5 };
        int n = arr.length;
        System.out.println(sumBitDifferences(arr, n));
    }
}
  
// This code is contributed by Sania Kumari Gupta (kriSania804)
 
 

Python3




# Python program to compute sum of pairwise bit differences
  
def sumBitDifferences(arr, n):
  
    ans = 0  # Initialize result
  
    # traverse over all bits
    for i in range(0, 32):
      
        # count number of elements with i'th bit set
        count = 0
        for j in range(0, n):
            if ( (arr[j] & (1 << i)) ):
                count+= 1
  
        # Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
      
    return ans
  
# Driver program
arr = [1, 3, 5]
n = len(arr )
print(sumBitDifferences(arr, n))
  
# This code is contributed by
# Smitha Dinesh Semwal    
 
 

C#




// C# program to compute sum
// of pairwise bit differences
using System;
  
class GFG {
    static int sumBitDifferences(int[] arr,
                                 int n)
    {
        int ans = 0; // Initialize result
  
        // traverse over all bits
        for (int i = 0; i < 32; i++) {
  
            // count number of elements
            // with i'th bit set
            int count = 0;
            for (int j = 0; j < n; j++)
                if ((arr[j] & (1 << i)) != 0)
                    count++;
  
            // Add "count * (n - count) * 2"
            // to the answer
            ans += (count * (n - count) * 2);
        }
  
        return ans;
    }
    // Driver Code
    public static void Main()
    {
  
        int[] arr = { 1, 3, 5 };
        int n = arr.Length;
  
        Console.Write(sumBitDifferences(arr, n));
    }
}
  
// This code is contributed by ajit
 
 

PHP




<?php
// PHP program to compute sum
// of pairwise bit differences
  
function sumBitDifferences($arr, $n)
{
    // Initialize result
    $ans = 0; 
  
    // traverse over all bits
    for ($i = 0; $i < 32; $i++)
    {
        // count number of elements
        // with i'th bit set
        $count = 0;
        for ($j = 0; $j < $n; $j++)
            if (($arr[$j] & (1 << $i)))
                $count++;
  
        // Add "count * (n - count) * 2"
        // to the answer
        $ans += ($count * ($n - 
                           $count) * 2);
    }
  
    return $ans;
}
  
// Driver Code
$arr = array(1, 3, 5);
$n = sizeof($arr);
echo sumBitDifferences($arr, $n), "\n";
  
// This code is contributed by m_kit
?>
 
 

Javascript




<script>
  
// Javascript program to compute sum
// of pairwise bit differences
function sumBitDifferences(arr, n)
{
      
    // Initialize result
    let ans = 0; 
  
    // Traverse over all bits
    for(let i = 0; i < 32; i++) 
    {
          
        // count number of elements with i'th bit set
        let count = 0;
        for(let j = 0; j < n; j++)
            if ((arr[j] & (1 << i)))
                count++;
  
        // Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
    }
    return ans;
}
  
// Driver code
let arr = [ 1, 3, 5 ];
let n = arr.length;
  
document.write(sumBitDifferences(arr, n));
  
// This code is contributed by subhammahato348
  
</script>
 
 
Output
8

Time Complexity: O(n)
Auxiliary Space: O(1)

Asked in: Google

Thanks to Gaurav Ahirwar for suggesting this solution.



Next Article
Minimum and Maximum sum of absolute differences of pairs
author
kartik
Improve
Article Tags :
  • Arrays
  • Bit Magic
  • DSA
  • Mathematical
  • Google
Practice Tags :
  • Google
  • Arrays
  • Bit Magic
  • Mathematical

Similar Reads

  • Sum of squares of differences between all pairs of an array
    Given an array arr[] of size N, the task is to compute the sum of squares of differences of all possible pairs. Examples: Input: arr[] = {2, 8, 4}Output: 56Explanation: Sum of squared differences of all possible pairs = (2 - 8)2 + (2 - 4)2 + (8 - 4)2 = 56 Input: arr[] = {-5, 8, 9, -4, -3}Output: 950
    9 min read
  • Minimum sum of all differences between unique pairs in the Array
    Given an array arr[] consisting of N integers, the task is to find the minimum sum of all absolute differences between unique pairs of elements in the array after updating the array arr[]. To update the array, any two elements from the array can be chosen in any order. 1 is subtracted from the first
    7 min read
  • 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
    14 min read
  • Minimum and Maximum sum of absolute differences of pairs
    Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -4
    8 min read
  • Sum of Bitwise And of all pairs in a given array
    Given an array "arr[0..n-1]" of integers, calculate sum of "arr[i] & arr[j]" for all the pairs in the given where i < j. Here & is bitwise AND operator. Expected time complexity is O(n). Examples : Input: arr[] = {5, 10, 15} Output: 15 Required Value = (5 & 10) + (5 & 15) + (10
    13 min read
  • Sum of absolute differences of all pairs in a given array
    Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array. Examples: Input : arr[] = {1, 2, 3, 4} Output: 10 Sum of |2-1| + |3-1| + |4-1| + |3-2| + |4-2| + |4-3| = 10 Input : arr[] = {1, 8, 9, 15, 16} Output: 74 Input : arr[]
    11 min read
  • Sum of bitwise AND of all subarrays
    Given an array consisting of N positive integers, find the sum of bit-wise and of all possible sub-arrays of the array. Examples: Input : arr[] = {1, 5, 8} Output : 15 Bit-wise AND of {1} = 1 Bit-wise AND of {1, 5} = 1 Bit-wise AND of {1, 5, 8} = 0 Bit-wise AND of {5} = 5 Bit-wise AND of {5, 8} = 0
    8 min read
  • Sum of subset differences
    Given a set S consisting of n numbers, find the sum of difference between last and first element of each subset. We find first and last element of every subset by keeping them in same order as they appear in input set S. i.e., sumSetDiff(S) = ? (last(s) - first(s)), where sum goes over all subsets s
    9 min read
  • Sum of XOR of all pairs in an array
    Given an array of n integers, find the sum of xor of all pairs of numbers in the array. Examples : Input : arr[] = {7, 3, 5}Output : 127 ^ 3 = 43 ^ 5 = 67 ^ 5 = 2Sum = 4 + 6 + 2 = 12Input : arr[] = {5, 9, 7, 6}Output : 475 ^ 9 = 129 ^ 7 = 147 ^ 6 = 15 ^ 7 = 25 ^ 6 = 39 ^ 6 = 15Sum = 12 + 14 + 1 + 2
    11 min read
  • Sum of Bitwise OR of all pairs in a given array
    Given an array "arr[0..n-1]" of integers. The task is to calculate the sum of Bitwise OR of all pairs, i.e. calculate the sum of "arr[i] | arr[j]" for all the pairs in the given array where i < j. Here '|' is a bitwise OR operator. The expected time complexity is O(n). Examples: Input: arr[] = {5
    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