[Geeks for Geeks] Sum of bit differences

Sum of bit differences

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).

Note: (x, y) and (y, x) are considered two separate pairs.

  • Time : O(n)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution{
public:
long long sumBitDifferences(int arr[], int n) {
vector<int> bit(32, 0);
vector<int> nbit(32, 0);
long long res = 0;
for(int i = 0; i < n; i++) {
long long sum = 0;
for(int j = 0; j < 32; j++) {
if(arr[i] & (1<<j)) {
bit[j]++;
res += nbit[j];
} else {
nbit[j]++;
res += bit[j];
}
}

}
return res * 2;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/27/PS/GeeksforGeeks/sum-of-bit-differences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.