Hamming Distance

Count the bit positions where two integers differ, with XOR and a loop that clears one 1 bit at a time.

Write two integers x and y in binary, as rows of bits (0s and 1s). Their Hamming distance is the number of positions where the two rows have different bits. Given x and y, return their Hamming distance.

Example 1
Input: x = 1, y = 4
Output: 2
Explanation: 1 is 0001 and 4 is 0100. They differ in two positions.
Example 2
Input: x = 3, y = 1
Output: 1
Explanation: 3 is 0011 and 1 is 0001. They differ in one position.
Solution

The Idea

Picture two rows of light switches, each switch either off (0) or on (1). The Hamming distance is how many switches you would have to flip to make one row look like the other. A number in binary is such a row: it uses only the digits 0 and 1, and each digit is called a bit.

Take Example 1. In binary, 1 is 0001 and 4 is 0100, showing the last four bits of each. Look at the picture below. The bits are numbered from the right, starting at 0, as the top row of the picture, labelled "bit position", shows.

1 is 0001 and 4 is 0100 in binary. They differ at bit positions 2 and 0. x ^ y = 5, which is 0101, has a 1 at exactly those two positions, so the Hamming distance is 2.

Compare the rows labelled x = 1 and y = 4 column by column. At position 2, x has a 0 and y has a 1. At position 0 it is the other way round. At positions 3 and 1 both have a 0. Two positions differ, so the answer is 2.

A program cannot glance at two rows the way we just did. It could compare them one position at a time, but is there a way to mark every differing position at once?

Java's ^ operator, called XOR (short for "exclusive or"), does exactly that. It walks along both numbers together and writes a 1 where their bits differ and a 0 where they match. The bottom row of the picture, labelled x ^ y = 5, is its result for 1 and 4: 0101, with a 1 at positions 2 and 0, the two columns marked "differ".

So the Hamming distance of x and y is the number of 1 bits in x ^ y. What was a question about two numbers becomes counting the 1 bits of one.

Solution Approach

What is left is counting the 1 bits in x ^ y, in a way that also works for negative numbers. The count can check every position, jump straight from one 1 bit to the next, or call a method that Java already has.

Checking every position

How would we count the 1 bits by hand? Store the result of x ^ y in a variable named diff, then look at position 0, position 1, and so on. In Java, (diff >> i) & 1 gives the bit at position i: the shift >> moves that bit to position 0, and & 1 keeps only position 0. A Java int has 32 positions, so checking every position always takes 32 steps, even when diff is 0101 with two 1 bits.

Clearing the lowest 1 bit

Can the count skip the 0 bits? It can, because diff & (diff - 1) is diff with its lowest 1 bit turned into a 0. Subtracting 1 turns the lowest 1 bit into a 0 and every 0 to its right into a 1, and leaves the bits further left alone. The AND operator & keeps a 1 only where both numbers have one. So the bits further left survive, and the lowest 1 bit and everything right of it become 0.

For diff = 0101, clearing takes two steps:

diff beforediff - 1diff after1 bits cleared
0101010001001
0100001100002

Each step removes exactly one 1 bit, so the number of steps until diff reaches 0 is the number of 1 bits. Counting this way is often called Brian Kernighan's trick.

Negative numbers

What if x or y is negative? A Java int is 32 bits in two's complement: a negative number -m is stored as the bit pattern of 232 - m. For -1 that is 232 - 1, which is 32 ones. XOR and the clearing step only look at bits, so they treat a negative diff like any other. The loop just has to stop when diff is 0, not when it stops being positive.

Optional: Java's built-in count

Java can also count the 1 bits for us. Integer.bitCount(x ^ y) returns the same number in a single call, so real code can use it. The clearing loop shows how such a count works.

Java Solution

The method hammingDistance works in these steps:

  1. First, XOR the two numbers with x ^ y and keep the result in diff. Each 1 bit in diff marks a position where x and y differ.
  2. Start a counter, count, at 0.
  3. Loop while diff is not 0. Each pass clears the lowest 1 bit with diff &= diff - 1 and adds 1 to count.
  4. When diff reaches 0, every 1 bit has been cleared once, so count is the Hamming distance, and the method returns it.

A helper method, show, prints a pair of numbers with the method's answer and, for comparison, what Integer.bitCount(x ^ y) gives. The main method calls it for both examples, two equal numbers, 0 against -1, and the largest int against the smallest, then prints -1 in binary.

Java
public class HammingDistance {

    public static int hammingDistance(int x, int y) {
        int diff = x ^ y;            // 1 exactly where the bits differ
        int count = 0;
        while (diff != 0) {
            diff &= diff - 1;        // clear the lowest 1 bit
            count++;
        }
        return count;
    }

    static void show(int x, int y) {
        System.out.println("x = " + x + ", y = " + y + ": " + hammingDistance(x, y)
                + " (bitCount says " + Integer.bitCount(x ^ y) + ")");
    }

    public static void main(String[] args) {
        show(1, 4);
        show(3, 1);
        show(7, 7);                                  // equal numbers
        show(0, -1);                                 // -1 has all 32 bits set
        show(Integer.MAX_VALUE, Integer.MIN_VALUE);  // every bit differs
        System.out.println(Integer.toBinaryString(-1));
    }
}

Running it prints:

Output
x = 1, y = 4: 2 (bitCount says 2)
x = 3, y = 1: 1 (bitCount says 1)
x = 7, y = 7: 0 (bitCount says 0)
x = 0, y = -1: 32 (bitCount says 32)
x = 2147483647, y = -2147483648: 32 (bitCount says 32)
11111111111111111111111111111111

The pairs 1, 4 and 3, 1 come out 2 and 1, as in the examples, and Integer.bitCount agrees on every line. For 7 and 7 the answer is 0: diff starts at 0, so the loop never runs.

Look at the last line, -1 written in binary: 32 ones. That is why 0 and -1 are 32 apart. The largest int, 2147483647, is a 0 followed by 31 ones, and the smallest, -2147483648, is a 1 followed by 31 zeros, so they differ in all 32 positions too.

Both of those pairs have a 1 at position 31, the leftmost, in diff, which makes diff negative. That is where the loop condition diff != 0 matters. Written as while (diff > 0), the method returns 0 for x = 0 and y = -1, because the loop never starts, while it still returns 2 for 1 and 4.

Complexity

The work is one XOR, plus one pass of the loop for each 1 bit in diff.

  • Time: O(1), because the loop runs once per position where x and y differ, and a 32-bit int has at most 32 such positions: 2 passes for 1 and 4, 32 for 0 and -1.
  • Space: O(1), because the method keeps only diff and count, whatever the two numbers are.

The same counting extends to every pair in a list of numbers in Total Hamming Distance.