Facebook Pixel

461. Hamming Distance

EasyBit Manipulation
Leetcode Link

Problem Description

The Hamming distance is a measure of difference between two integers at the binary level. It counts how many bit positions have different values when comparing the binary representations of two numbers.

Given two integers x and y, you need to find and return their Hamming distance.

For example, if x = 1 and y = 4:

  • Binary representation of 1 is 0001
  • Binary representation of 4 is 0100
  • Comparing bit by bit: position 0 differs (1 vs 0) and position 2 differs (0 vs 1)
  • Therefore, the Hamming distance is 2

The solution uses the XOR operation (x ^ y) which produces a 1 in each bit position where x and y differ, and 0 where they are the same. Then bit_count() counts the number of 1s in the result, giving us the Hamming distance directly.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

To find how many bits are different between two numbers, we need to compare them bit by bit. The key insight is recognizing that the XOR operation naturally does this comparison for us.

When we XOR two bits:

  • 0 ^ 0 = 0 (same bits)
  • 1 ^ 1 = 0 (same bits)
  • 0 ^ 1 = 1 (different bits)
  • 1 ^ 0 = 1 (different bits)

This means XOR produces a 1 exactly when the bits differ and 0 when they're the same. So if we perform x ^ y, we get a number where each 1 bit represents a position where x and y have different bits.

For example, with x = 5 (binary: 101) and y = 1 (binary: 001):

  • 5 ^ 1 = 101 ^ 001 = 100 (binary)
  • The result has one 1 bit, indicating one position where the numbers differ

Now we just need to count how many 1s are in the XOR result. This is exactly what bit_count() does - it counts the number of set bits (1s) in a number. The count of 1s in x ^ y gives us the Hamming distance directly.

This approach elegantly reduces the problem to two simple operations: XOR to identify differences, then count the differences.

Solution Approach

The implementation is remarkably concise, leveraging Python's built-in bit manipulation capabilities:

def hammingDistance(self, x: int, y: int) -> int:
    return (x ^ y).bit_count()

Let's break down the solution step by step:

  1. XOR Operation (x ^ y): We perform a bitwise XOR between x and y. This operation compares each corresponding bit position of the two numbers and produces:

    • 1 if the bits are different
    • 0 if the bits are the same
  2. Count Set Bits (bit_count()): The bit_count() method counts the number of 1s in the binary representation of the XOR result. This directly gives us the Hamming distance.

Example walkthrough:

Let's trace through x = 1 and y = 4:

  • x = 1 in binary: 0001
  • y = 4 in binary: 0100
  • x ^ y = 0001 ^ 0100 = 0101 (decimal 5)
  • (0101).bit_count() = 2 (there are two 1s)
  • Result: Hamming distance is 2

Time Complexity: O(1) - The XOR operation and bit counting both operate in constant time for fixed-size integers.

Space Complexity: O(1) - We only use a constant amount of extra space to store the XOR result.

This solution elegantly combines two fundamental bit operations to solve the problem in a single line, making it both efficient and easy to understand.

Ready to land your dream job?

Unlock your dream job with a 3-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with x = 3 and y = 7:

Step 1: Convert to binary representation

  • x = 3 → binary: 011
  • y = 7 → binary: 111

Step 2: Perform XOR operation (x ^ y)

  • Line up the bits and XOR each position:
  011 (x = 3)
^ 111 (y = 7)
------
  100 (result = 4)
  • Position 0: 1 ^ 1 = 0 (same bits)
  • Position 1: 1 ^ 1 = 0 (same bits)
  • Position 2: 0 ^ 1 = 1 (different bits)

Step 3: Count the 1s in XOR result

  • XOR result is 100 (decimal 4)
  • Count of 1s: bit_count(100) = 1

Result: Hamming distance = 1

The two numbers differ in exactly one bit position (position 2), so their Hamming distance is 1.

This demonstrates how the XOR operation highlights the differences between the two numbers, and counting those differences gives us the Hamming distance directly.

Solution Implementation

1class Solution:
2    def hammingDistance(self, x: int, y: int) -> int:
3        """
4        Calculate the Hamming distance between two integers.
5      
6        The Hamming distance is the number of positions at which 
7        the corresponding bits are different.
8      
9        Args:
10            x: First integer
11            y: Second integer
12          
13        Returns:
14            The number of bit positions where x and y differ
15        """
16        # XOR operation highlights the differing bits (sets them to 1)
17        xor_result = x ^ y
18      
19        # Count the number of 1s in the XOR result
20        # bit_count() returns the number of set bits (1s) in the binary representation
21        return xor_result.bit_count()
22
1class Solution {
2    /**
3     * Calculates the Hamming distance between two integers.
4     * The Hamming distance is the number of positions at which 
5     * the corresponding bits are different.
6     * 
7     * @param x The first integer
8     * @param y The second integer
9     * @return The number of bit positions where x and y differ
10     */
11    public int hammingDistance(int x, int y) {
12        // XOR operation highlights the bits that are different between x and y
13        // When bits are the same, XOR yields 0; when different, XOR yields 1
14        int xorResult = x ^ y;
15      
16        // Count the number of 1s in the XOR result
17        // This gives us the count of differing bit positions
18        return Integer.bitCount(xorResult);
19    }
20}
21
1class Solution {
2public:
3    /**
4     * Calculate the Hamming distance between two integers.
5     * The Hamming distance is the number of positions at which 
6     * the corresponding bits are different.
7     * 
8     * @param x First integer
9     * @param y Second integer
10     * @return The number of bit positions where x and y differ
11     */
12    int hammingDistance(int x, int y) {
13        // XOR operation highlights the differing bits (sets them to 1)
14        // __builtin_popcount counts the number of set bits (1s)
15        return __builtin_popcount(x ^ y);
16    }
17};
18
1/**
2 * Calculates the Hamming distance between two integers.
3 * The Hamming distance is the number of positions at which the corresponding bits are different.
4 * 
5 * @param x - The first integer
6 * @param y - The second integer
7 * @returns The Hamming distance between x and y
8 */
9function hammingDistance(x: number, y: number): number {
10    // XOR the two numbers to get a value where set bits represent differing positions
11    x ^= y;
12  
13    // Initialize counter for the number of differing bits
14    let bitDifferenceCount: number = 0;
15  
16    // Count the number of set bits using Brian Kernighan's algorithm
17    // This efficiently removes the rightmost set bit in each iteration
18    while (x) {
19        // Remove the rightmost set bit
20        // x & -x isolates the rightmost set bit, subtracting it removes that bit
21        x -= x & -x;
22      
23        // Increment the counter for each set bit found
24        ++bitDifferenceCount;
25    }
26  
27    return bitDifferenceCount;
28}
29

Time and Space Complexity

Time Complexity: O(1)

The solution uses XOR operation (x ^ y) followed by bit_count(). The XOR operation between two integers is O(1) since it operates on a fixed number of bits (32 bits for standard integers in most systems). The bit_count() method counts the number of set bits (1s) in the binary representation, which also takes O(1) time for fixed-size integers as it processes a constant number of bits.

Space Complexity: O(1)

The algorithm uses only a constant amount of extra space. The XOR operation produces a single integer result, and bit_count() returns a single integer count. No additional data structures or recursive calls are used that would scale with input size.

Common Pitfalls

1. Python Version Compatibility Issue

The bit_count() method was introduced in Python 3.10. If you're using an earlier version of Python, this code will raise an AttributeError.

Error Example:

# In Python < 3.10
return (x ^ y).bit_count()  # AttributeError: 'int' object has no attribute 'bit_count'

Solution: For compatibility with older Python versions, use alternative approaches:

# Option 1: Using bin() and count()
def hammingDistance(self, x: int, y: int) -> int:
    return bin(x ^ y).count('1')

# Option 2: Manual bit counting (Brian Kernighan's algorithm)
def hammingDistance(self, x: int, y: int) -> int:
    xor_result = x ^ y
    count = 0
    while xor_result:
        xor_result &= xor_result - 1  # Clear the rightmost set bit
        count += 1
    return count

# Option 3: Bit shifting approach
def hammingDistance(self, x: int, y: int) -> int:
    xor_result = x ^ y
    count = 0
    while xor_result:
        count += xor_result & 1
        xor_result >>= 1
    return count

2. Negative Number Handling

While the problem typically assumes non-negative integers, if negative numbers are involved, Python's handling of negative integers in binary (using two's complement with unlimited precision) might produce unexpected results.

Example:

# With negative numbers
x = -1  # In binary: ...11111111 (infinite 1s to the left)
y = 0   # In binary: ...00000000
# The XOR would theoretically have infinite 1s, causing issues

Solution: Add input validation or mask the result to a fixed bit width:

def hammingDistance(self, x: int, y: int) -> int:
    # Mask to 32-bit integers if dealing with potentially negative values
    mask = 0xFFFFFFFF
    return ((x & mask) ^ (y & mask)).bit_count()

3. Large Integer Performance

For very large integers, the bit operations might take longer than expected, though this is rare in typical LeetCode constraints.

Solution: If dealing with arbitrarily large integers, consider adding bounds checking or documenting the expected input range to set proper expectations for performance.

Discover Your Strengths and Weaknesses: Take Our 3-Minute Quiz to Tailor Your Study Plan:

In a binary min heap, the minimum element can be found in:


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More