Hamming Distance (LeetCode 461): Solution and Explanation
Return the number of bit positions where the binary forms of x and y differ.
Intuition
Write x and y in binary, one above the other, and compare column by column. The answer is how many columns disagree.
XOR does that comparison for all columns at once: a bit of x ^ y is 1 when the two bits differ and 0 when they match. So the problem turns into counting the 1 bits of z = x ^ y.
To count them, the neat trick is z & (z - 1). Subtracting 1 flips the lowest 1 of z to 0 and the 0s below it to 1s, and the AND then wipes that whole tail, so exactly one 1 disappears each time. Count how many times you can do it before z is 0.
Approach: XOR plus Brian Kernighan bit count
- Compute
z = x ^ y. Its 1 bits are exactly the differing positions. - Set
count = 0. - While
zis not 0, doz &= z - 1(drop the lowest 1) and add 1 tocount. - Return
count.
Step-by-step example
x = 1, y = 4
- x = 0001, y = 0100. They differ at bit 0 and bit 2.
- z = x ^ y = 0101 = 5.
- z & (z - 1) = 0101 & 0100 = 0100. Bit 0 is gone, count = 1.
- z & (z - 1) = 0100 & 0011 = 0000. Bit 2 is gone, count = 2.
- z is 0, so return 2.
Code: Python, Java, C++
1class Solution:
2 def hammingDistance(self, x: int, y: int) -> int:
3 z = x ^ y
4 count = 0
5 while z:
6 z &= z - 1
7 count += 1
8 return count1class Solution {
2 public int hammingDistance(int x, int y) {
3 int z = x ^ y;
4 int count = 0;
5 while (z != 0) {
6 z &= z - 1;
7 count++;
8 }
9 return count;
10 }
11}1class Solution {
2public:
3 int hammingDistance(int x, int y) {
4 int z = x ^ y;
5 int count = 0;
6 while (z != 0) {
7 z &= z - 1;
8 count++;
9 }
10 return count;
11 }
12};Time and space complexity
O(1)
The loop runs once per differing bit, at most 31 times for these inputs.
O(1)
Only z and count are stored.
Other approaches
Shift and test every bit (time O(32), space O(1))
Loop 32 times, add (z >> i) & 1 to the count. Always 32 iterations, but very easy to read.
Built-in popcount (time O(1), space O(1))
bin(x ^ y).count('1') in Python, Integer.bitCount in Java, __builtin_popcount in C++, bits.OnesCount in Go. Shortest and usually compiled to a single CPU instruction.
Common mistakes
- Using OR or AND instead of XOR. Only XOR marks positions where exactly one of the two numbers has a 1.
- Shifting a negative value with >> in Java or JavaScript loops forever because the sign bit is copied in. It cannot happen here since x and y are non-negative, but >>> is the safe shift when it can.
- Comparing the decimal digits or the binary strings without padding. The shorter number has leading zeros, so 1 against 4 compares 001 with 100, not 1 with 100. XOR handles this automatically.
Frequently asked questions
Why does z & (z - 1) remove exactly one bit?
Subtracting 1 borrows from the lowest 1: that bit becomes 0 and every 0 below it becomes 1. Bits above it are unchanged. ANDing with the original keeps the upper bits and clears the rest, so only the lowest 1 is lost.
Is this faster than checking all 32 bits?
It runs once per differing bit instead of once per bit position. For inputs that differ in only a few places that is much less work, though both are constant time here.
What is the Hamming distance used for?
It measures how many bits flipped between two codes, which is the basis of error-detecting and error-correcting codes and of similarity checks on binary fingerprints.