Hamming Distance
Hamming Distance is a easy bit manipulation problem solved with the xor basics pattern.
The best approach, optimal (xor, then count set bits), runs in O(number of differing bits) time and O(1) space.
Below are 2 approaches in Java, from compare bit by bit up.
Problem
The Hamming distance between two integers is the number of bit positions where they differ. Return it.
Examples
Example 1
- Input
x = 1, y = 4- Output
2- Why
- 001 vs 100: two positions differ.
Example 2
- Input
x = 3, y = 1- Output
1
Constraints
0 <= x, y <= 2^31 - 1
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the Java code.
| Approach | Time | Space |
|---|---|---|
| Compare bit by bit | O(32) | O(1) |
| Optimal (XOR, then count set bits) | O(number of differing bits) | O(1) |
1Compare bit by bit
O(32)O(1)Check each of the 32 positions.
- For i in 0..31: if ((x >> i) & 1) != ((y >> i) & 1), count++.
class Solution {
public int hammingDistance(int x, int y) {
int count = 0;
for (int i = 0; i < 32; i++) if (((x >> i) & 1) != ((y >> i) & 1)) count++;
return count;
}
}2Optimal (XOR, then count set bits)
O(number of differing bits)O(1)XOR marks the differing bits; Kernighan's trick counts them.
- d = x ^ y; while d != 0: d &= d - 1; count++.
class Solution {
public int hammingDistance(int x, int y) {
int d = x ^ y, count = 0;
while (d != 0) {
d &= d - 1;
count++;
}
return count;
}
}Edge cases to test
- x == y (0)
Hints
Hint 1
x ^ y has a 1 exactly where the bits differ. Count its set bits.
FAQ
What is the best time complexity for Hamming Distance?
Optimal (XOR, then count set bits) runs in O(number of differing bits) time and O(1) extra space.
Which pattern does Hamming Distance use?
It is a bit manipulation problem that uses the xor basics pattern. Other problems with the same pattern: Swap two numbers.
Is there a brute force solution for Hamming Distance?
Yes. Compare bit by bit takes O(32) time and O(1) space. Check each of the 32 positions.
Which edge cases should I test for Hamming Distance?
x == y (0).