Leetcode 477. Total Hamming Distance
Given an integer array nums
, return the sum of Hamming distances between all the pairs of the integers in nums
.
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
nums
) and the values within the array?
nums.length
can range from 1 to 10^4 and values in nums
can be as large as 10^9.nums
.nums
and M is the number of bits (around 30 for integers up to 10^9).Here’s the implementation of the efficient approach:
public class Solution {
public int totalHammingDistance(int[] nums) {
int total = 0;
int n = nums.length;
// There are 30 bits to consider (since numbers are <= 10^9)
for (int i = 0; i < 30; ++i) {
int countOne = 0;
for (int num : nums) {
countOne += (num >> i) & 1;
}
int countZero = n - countOne;
total += countOne * countZero;
}
return total;
}
}
nums
array. This is because for each of the 30 bit positions, we are iterating through the array once.This solution efficiently computes the total Hamming distance by leveraging bit manipulation and avoids the quadratic time complexity of the brute-force approach.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?