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, return the sum of the Hamming distances over all pairs of numbers in it. The array holds at most 10,000 numbers.

Example 1
Input: nums = [4, 14, 2]
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
Input: nums = [4, 14, 4]
Output: 4
Solution

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.

The numbers 4, 14 and 2 in binary as 0100, 1110 and 0010, with bit positions 3 to 0. Under each position: how many numbers have a 1 there, and how many pairs differ there (2, 2, 2 and 0). The column labelled bit 1 is highlighted, and the total is 6.

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 ^ b (XOR) gives a number with a 1 exactly where a and b differ: 4 ^ 14 is 1010. Then Integer.bitCount counts those ones, 2 here.

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 slides every bit of 1110 one place to the right and fills the left side with 0, giving 0111. Now the bit we wanted sits at position 0. Then & 1 keeps only position 0 and clears the rest, so (14 >>> 1) & 1 is 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 needed.

Which bit positions to check

The picture shows only four positions, because 4, 14 and 2 fit in four bits. A Java int has 32 bits, though, and the other 28 positions of these three numbers are all 0, so each adds 0 × 3 = 0 pairs.

Negative numbers do use the high positions. Java stores a negative int in two's complement, where -1 is 32 ones and -2 is 31 ones followed by a 0 at position 0. So 0 and -1 differ at every one of the 32 positions. Checking all 32 positions for every input handles these numbers with no special case.

Keeping the total in an int

Can the total grow past what an int holds? At one position, the product of ones and zeros is largest when the numbers split evenly. With 10,000 numbers that is 5,000 × 5,000 = 25,000,000 pairs. Over 32 positions it is at most 800,000,000, which is below the int limit of 2,147,483,647, so an int total is safe here.

Java Solution

The method totalHammingDistance works in these steps:

  1. First, store the length of the array in n and start the answer, total, at 0.
  2. A loop moves bit through the 32 positions, from 0 to 31.
  3. For each position, set ones to 0. Inside, a second loop goes over every number num and adds (num >>> bit) & 1 to ones, so ones ends up as the count of numbers with a 1 at this position.
  4. The other n - ones numbers have a 0 there, so add ones * (n - ones) to total.
  5. After all 32 positions, return total.

The main method runs both examples, a single number, an empty array and [-1, 0]. For [-1, 1, -2] and for 10,000 numbers, half 0 and half -1, it prints the answer next to the slow count from pairByPair, which compares every pair with XOR and Integer.bitCount.

Java
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:

Output
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] and the empty array both print 0: with fewer than two numbers, ones * (n - ones) is 0 at every position.

The 32 comes from [-1, 0], where every position holds a 1 in -1 and a 0 in 0. On the line 64 64, both ways agree for [-1, 1, -2]: -1 and 1 differ at 31 positions, -1 and -2 only at position 0, and 1 and -2 at all 32.

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 int total of 800,000,000 matches the long count from pairByPair.

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, ones and total, however long the array is.

For the distance between just two numbers, see Hamming Distance.