[InterviewBit] Sum of pairwise Hamming Distance

Sum of pairwise Hamming Distance

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int Solution::hammingDistance(const vector<int> &A) {
long long n = A.size(), res = 0, mod = 1e9 + 7;
vector<int> freq(32);
for(auto a : A) {
for(int i = 0; i < 32; i++) {
if(a & (1<<i)) freq[i]++;
}
}
for(auto a : A) {
for(int i = 0; i < 32; i++) {
if(a & (1<<i)) res = (res + n - freq[i]) % mod;
else res = (res + freq[i]) % mod;
}
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/18/PS/interviewbit/sum-of-pairwise-hamming-distance/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.