# Sum of bit differences among all pairs

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

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(n^{2}).

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

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 prorgram
int main()
{
int arr[] = {1, 3, 5};
int n = sizeof arr / sizeof arr[0];
cout << sumBitDifferences(arr, n) << endl;
return 0;
}
[tabby title="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
ans += (count * (n - count) * 2);
}
return ans;
}
// Driver prorgram
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 Anshika Goyal.
[tabby title="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 prorgram
arr = [1, 3, 5]
n = len(arr )
print(sumBitDifferences(arr, n))
# This code is contributed by
# Smitha Dinesh Semwal
[tabby title="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
[tabby title="PHP"]

**Output :**

8

### Asked in: Google

Thanks to Gaurav Ahirwar for suggesting this solution.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

## Recommended Posts:

- Sum of absolute differences of all pairs in a given array
- Minimum and Maximum sum of absolute differences of pairs
- Find the maximum cost of an array of pairs choosing at most K pairs
- Ways to form n/2 pairs such that difference of pairs is minimum
- Sum of subset differences
- What are the differences between bitwise and logical AND operators in C/C++?
- Minimum sum of differences with an element in an array
- Maximize sum of consecutive differences in a circular array
- Array element with minimum sum of absolute differences
- Sequence with sum K and minimum sum of absolute differences between consecutive elements
- Clustering/Partitioning an array such that sum of square differences is minimum
- Differences between number of increasing subarrays and decreasing subarrays in k sized windows
- Sum of XOR of all pairs in an array
- Sum of XOR of sum of all pairs in an array
- Count pairs with given sum