Hamming Distance - Problem
The Hamming distance is a fundamental concept in computer science and information theory that measures how "different" two binary representations are. Given two integers x and y, you need to find the number of bit positions where these two numbers differ.
What you need to do:
- Compare the binary representations of two integers bit by bit
- Count how many positions have different bits (0 vs 1 or 1 vs 0)
- Return this count as the Hamming distance
Example: If x = 1 (binary: 001) and y = 4 (binary: 100), they differ in 2 positions, so the Hamming distance is 2.
This problem is commonly used in error detection, data compression, and cryptography!
Input & Output
example_1.py โ Basic Case
$
Input:
x = 1, y = 4
โบ
Output:
2
๐ก Note:
1 in binary is 001, 4 in binary is 100. They differ at positions 0 and 2 (counting from right), so the Hamming distance is 2.
example_2.py โ Same Numbers
$
Input:
x = 3, y = 3
โบ
Output:
0
๐ก Note:
Since both numbers are identical, their binary representations are the same. No positions differ, so the Hamming distance is 0.
example_3.py โ Powers of 2
$
Input:
x = 1, y = 8
โบ
Output:
2
๐ก Note:
1 is 0001 and 8 is 1000 in binary. They differ at the rightmost position (0 vs 1) and leftmost position (1 vs 0), giving a Hamming distance of 2.
Visualization
Tap to expand
Understanding the Visualization
1
Sequence Alignment
Align the two binary sequences (DNA strands) position by position
2
Mutation Detection
Use XOR as a 'mutation scanner' that highlights all positions with differences
3
Count Mutations
Count the total number of highlighted positions to get the mutation count
Key Takeaway
๐ฏ Key Insight: XOR operation naturally detects differences - it's like having a biological scanner that automatically highlights every position where DNA sequences differ, then we just count the highlights!
Time & Space Complexity
Time Complexity
O(1)
Using built-in popcount is constant time, or O(number of 1-bits) with Brian Kernighan's algorithm
โ Linear Growth
Space Complexity
O(1)
Only using a constant amount of extra space
โ Linear Space
Constraints
- 0 โค x, y โค 231 - 1
- Both integers are non-negative
- Follow-up: Can you solve this in O(1) time?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code