Total Hamming Distance

medium array math bit manipulation

Problem

Given an integer array nums, return the sum of Hamming distances between all the pairs of integers in nums.

Inputnums = [4, 14, 2]
Output6
HD(4,14)+HD(4,2)+HD(14,2) = 2 + 2 + 2 = 6. Or: at each bit, count ones k, zeros n−k; contribute k·(n−k).

def total_hamming_distance(nums):
    n = len(nums)
    total = 0
    for b in range(32):
        ones = sum((x >> b) & 1 for x in nums)
        total += ones * (n - ones)
    return total
function totalHammingDistance(nums) {
  const n = nums.length;
  let total = 0;
  for (let b = 0; b < 32; b++) {
    let ones = 0;
    for (const x of nums) ones += (x >> b) & 1;
    total += ones * (n - ones);
  }
  return total;
}
class Solution {
    public int totalHammingDistance(int[] nums) {
        int n = nums.length, total = 0;
        for (int b = 0; b < 32; b++) {
            int ones = 0;
            for (int x : nums) ones += (x >> b) & 1;
            total += ones * (n - ones);
        }
        return total;
    }
}
int totalHammingDistance(vector<int>& nums) {
    int n = nums.size(), total = 0;
    for (int b = 0; b < 32; b++) {
        int ones = 0;
        for (int x : nums) ones += (x >> b) & 1;
        total += ones * (n - ones);
    }
    return total;
}
Time: O(n · 32) Space: O(1)