Total Hamming Distance
Add up the bit differences of every pair of numbers by counting ones at one bit position at a time.
Write two integers in binary and count the positions where their bits differ: that count is their Hamming distance. Given an array of integers nums
Example 1
Output: 6
Explanation: in binary the numbers are 0100, 1110 and 0010. The distances are (4, 14) = 2, (4, 2) = 2 and (14, 2) = 2.
Example 2
Output: 4
The Idea
Think of each number as a row of on and off switches. 4 is 0100 in binary, and 14 is 1110. Put the two rows one above the other and the switches disagree in two places, the first and the third digit from the left. So the Hamming distance between 4 and 14 is 2.
Example 1 has three numbers, so there are three pairs, and each pair disagrees in two places, for a total of 6. Three pairs are easy to check one by one. With 10,000 numbers, though, there are 49,995,000 pairs. Can we get the total without looking at every pair?
Turn the question around. Instead of taking one pair and checking all its bits, take one bit position and check all the numbers. In the picture below, the bit positions are numbered from the right, so position 0 is the last digit.
Look at the highlighted column labelled bit 1. Here 14 and 2 have a 1, and 4 has a 0. Which pairs differ at this position? Exactly the pairs that take one number with a 1 and one with a 0: (14, 4) and (2, 4). The pair (14, 2) has a 1 in both, so it agrees here.
So the count of differing pairs at a position is the numbers with a 1 times the numbers with a 0, here 2 × 1 = 2. The row labelled "pairs that differ here" does the same for every column. At bit 0 all three numbers have a 0, so 0 × 3 = 0 pairs differ there. The four columns add up to 2 + 2 + 2 + 0 = 6, the answer to Example 1.
Counting the ones in a column takes a single look at each number. The pairs never have to be listed at all.
Solution Approach
Comparing every pair works, but it is slow. Counting by column instead leaves three things to settle: how to read one bit of a number, which bit positions to check, and whether the total fits in an int
Comparing every pair
What would the direct way look like? Two loops, one inside the other, pick every pair. For each pair, a ^ bab4 ^ 14Integer.bitCount
That is correct, but the work grows with the number of pairs, about n²/2 for n numbers. Counting by column grows with n instead, so the pair-by-pair way is kept only to check the answers.
Reading one bit
How do we read, say, bit 1 of 14? The shift 14 >>> 1& 1(14 >>> 1) & 1
That result is 1 or 0, so adding it up over all the numbers counts the ones in the column directly, with no if
Which bit positions to check
The picture shows only four positions, because 4, 14 and 2 fit in four bits. A Java int
Negative numbers do use the high positions. Java stores a negative int
Keeping the total in an int
Can the total grow past what an intintint
Java Solution
The method totalHammingDistance
- First, store the length of the array in
and start the answer,n , at 0.total - A loop moves
through the 32 positions, from 0 to 31.bit - For each position, set
to 0. Inside, a second loop goes over every numberones and addsnum to(num >>> bit) & 1 , soones ends up as the count of numbers with a 1 at this position.ones - The other
numbers have a 0 there, so addn - ones toones * (n - ones) .total - After all 32 positions, return
.total
The main[-1, 0][-1, 1, -2]pairByPairInteger.bitCount
public class TotalHammingDistance {
public static int totalHammingDistance(int[] nums) {
int n = nums.length;
int total = 0;
for (int bit = 0; bit < 32; bit++) {
int ones = 0;
for (int num : nums) {
ones += (num >>> bit) & 1; // 1 if this number has a 1 at this bit
}
total += ones * (n - ones); // pairs with one 1 and one 0 here
}
return total;
}
// the slow way, for comparison: every pair, one at a time
static long pairByPair(int[] nums) {
long total = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
total += Integer.bitCount(nums[i] ^ nums[j]);
}
}
return total;
}
public static void main(String[] args) {
System.out.println(totalHammingDistance(new int[] {4, 14, 2}));
System.out.println(totalHammingDistance(new int[] {4, 14, 4}));
System.out.println(totalHammingDistance(new int[] {7}));
System.out.println(totalHammingDistance(new int[] {}));
System.out.println(totalHammingDistance(new int[] {-1, 0}));
int[] mixed = {-1, 1, -2};
System.out.println(totalHammingDistance(mixed) + " " + pairByPair(mixed));
int[] halves = new int[10000]; // 5,000 zeros, then 5,000 copies of -1
java.util.Arrays.fill(halves, 5000, 10000, -1);
System.out.println(totalHammingDistance(halves) + " " + pairByPair(halves));
}
}
Running it prints:
6
4
0
0
32
64 64
800000000 800000000
The 6 and the 4 at the top match the two examples. In Example 2 the two copies of 4 agree at every position, so only the two pairs that include 14 count, 2 each. The single number [7]ones * (n - ones)
The 32 comes from [-1, 0]64 64[-1, 1, -2]
The last line is the largest total this problem allows. Each of the 32 positions has 5,000 ones and 5,000 zeros, so 25,000,000 pairs differ there, and the intlongpairByPair
Complexity
Each of the 32 bit positions gets one pass over the numbers, whatever the numbers are.
- Time: O(32 · n), which is O(n), because each of the 32 positions reads every one of the n numbers once, instead of visiting all n(n - 1)/2 pairs.
- Space: O(1), because the method keeps only
,bit andones , however long the array is.total
For the distance between just two numbers, see