Sum of bit differences among all pairs
Last Updated : 05 Aug, 2024
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
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++
#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++) { int x = a[i] & a[j]; int y = a[i] | a[j]; bitset<32> b1(x); bitset<32> b2(y); int r1 = b1.count(); int r2 = b2.count(); count = abs (r1 - r2); ans = ans + (2 * count); } } return ans; } int main() { vector< int > nums{ 10, 5 }; int ans = sum_bit_diff(nums); cout << ans; } |
Java
import java.io.*; class GFG { static int sumBitDiff( int [] arr){ int diff = 0 ; for ( int i= 0 ; i<arr.length; i++){ for ( int j=i; j<arr.length; j++){ int xor = arr[i]^arr[j]; int count = countSetBits(xor); diff += 2 *count; } } return diff; } static int countSetBits( int n){ int count = 0 ; while (n != 0 ) { n = n & (n - 1 ); count++; } return count; } public static void main (String[] args) { int [] arr = { 5 , 10 }; int ans = sumBitDiff(arr); System.out.println(ans); } } |
Python3
def sumBitDiff(arr): diff = 0 for i in range ( len (arr)): for j in range (i, len (arr)): xor = arr[i]^arr[j] count = countSetBits(xor) diff + = ( 2 * count) return diff def countSetBits(n): count = 0 while (n ! = 0 ) : n = n & (n - 1 ) count + = 1 return count if __name__ = = "__main__" : arr = [ 5 , 10 ] ans = sumBitDiff(arr) print (ans) |
C#
using System; public class GFG { static int sumBitDiff( int [] arr){ int diff = 0; for ( int i=0; i<arr.Length; i++){ for ( int j=i; j<arr.Length; j++){ int xor = arr[i]^arr[j]; int count = countSetBits(xor); diff += 2*count; } } return diff; } static int countSetBits( int n){ int count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } public static void Main(String[] args) { int [] arr = {5,10}; int ans = sumBitDiff(arr); Console.WriteLine(ans); } } |
Javascript
<script> function sumBitDiff(arr) { let diff = 0; for (let i = 0; i < arr.length; i++){ for (let j = i; j < arr.length; j++){ let xor = arr[i]^arr[j]; let count = countSetBits(xor); diff += 2*count; } } return diff; } function countSetBits(n){ let count = 0; while (n != 0) { n = n & (n - 1); count++; } return count; } let arr = [5,10]; let ans = sumBitDiff(arr); document.write(ans); </script> |
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++
#include <bits/stdc++.h> using namespace std; int sumBitDifferences( int arr[], int n) { int ans = 0; for ( int i = 0; i < 32; i++) { int count = 0; for ( int j = 0; j < n; j++) if ((arr[j] & (1 << i))) count++; ans += (count * (n - count) * 2); } return ans; } int main() { int arr[] = { 1, 3, 5 }; int n = sizeof arr / sizeof arr[0]; cout << sumBitDifferences(arr, n) << endl; return 0; } |
C
#include <stdio.h> int sumBitDifferences( int arr[], int n) { int ans = 0; for ( int i = 0; i < 32; i++) { int count = 0; for ( int j = 0; j < n; j++) if ((arr[j] & (1 << i))) count++; ans += (count * (n - count) * 2); } return ans; } int main() { int arr[] = { 1, 3, 5 }; int n = sizeof arr / sizeof arr[0]; printf ( "%d\n" , sumBitDifferences(arr, n)); return 0; } |
Java
import java.io.*; class GFG { static int sumBitDifferences( int arr[], int n) { int ans = 0 ; for ( int i = 0 ; i < 32 ; i++) { int count = 0 ; for ( int j = 0 ; j < n; j++) if ((arr[j] & ( 1 << i)) != 0 ) count++; ans += (count * (n - count) * 2 ); } return ans; } public static void main(String args[]) { int arr[] = { 1 , 3 , 5 }; int n = arr.length; System.out.println(sumBitDifferences(arr, n)); } } |
Python3
def sumBitDifferences(arr, n): ans = 0 for i in range ( 0 , 32 ): count = 0 for j in range ( 0 , n): if ( (arr[j] & ( 1 << i)) ): count + = 1 ans + = (count * (n - count) * 2 ); return ans arr = [ 1 , 3 , 5 ] n = len (arr ) print (sumBitDifferences(arr, n)) |
C#
using System; class GFG { static int sumBitDifferences( int [] arr, int n) { int ans = 0; for ( int i = 0; i < 32; i++) { int count = 0; for ( int j = 0; j < n; j++) if ((arr[j] & (1 << i)) != 0) count++; ans += (count * (n - count) * 2); } return ans; } public static void Main() { int [] arr = { 1, 3, 5 }; int n = arr.Length; Console.Write(sumBitDifferences(arr, n)); } } |
PHP
<?php function sumBitDifferences( $arr , $n ) { $ans = 0; for ( $i = 0; $i < 32; $i ++) { $count = 0; for ( $j = 0; $j < $n ; $j ++) if (( $arr [ $j ] & (1 << $i ))) $count ++; $ans += ( $count * ( $n - $count ) * 2); } return $ans ; } $arr = array (1, 3, 5); $n = sizeof( $arr ); echo sumBitDifferences( $arr , $n ), "\n" ; ?> |
Javascript
<script> function sumBitDifferences(arr, n) { let ans = 0; for (let i = 0; i < 32; i++) { let count = 0; for (let j = 0; j < n; j++) if ((arr[j] & (1 << i))) count++; ans += (count * (n - count) * 2); } return ans; } let arr = [ 1, 3, 5 ]; let n = arr.length; document.write(sumBitDifferences(arr, n)); </script> |
Time Complexity: O(n)
Auxiliary Space: O(1)
Thanks to Gaurav Ahirwar for suggesting this solution.
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