#461

Hamming Distance

Easy
Bit ManipulationBit ManipulationXOR
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(32) or O(1)
O(1)
Space
O(1)
O(1)
💡

Intuition

Time O(1)Space O(1)

The optimal solution uses the XOR operation to find differing bits directly. By XORing the two numbers, we can identify all the differing bits in one go, making the solution more efficient.

⚙️

Algorithm

2 steps
  1. 1Step 1: Perform XOR between x and y to get a number that has bits set to 1 where x and y differ.
  2. 2Step 2: Count the number of 1s in the result of the XOR operation.
solution.py4 lines
1# Full working Python code
2
3def hamming_distance(x, y):
4    return bin(x ^ y).count('1')

Complexity note: The time complexity is O(1) because the operations performed (XOR and counting bits) are constant time operations. The space complexity is O(1) as we are using a fixed amount of space.

  • 1XOR operation is a powerful tool for bit manipulation.
  • 2Counting bits can be efficiently done using built-in functions.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.