Hamming Distance - Problem

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Example: For x = 1 (binary: 0001) and y = 4 (binary: 0100), the Hamming distance is 2 because bits differ at positions 0 and 2.

Input & Output

Example 1 — Basic Case
$ Input: x = 1, y = 4
Output: 2
💡 Note: x = 1 (binary: 0001), y = 4 (binary: 0100). Bits differ at positions 0 and 2, so Hamming distance = 2
Example 2 — Same Numbers
$ Input: x = 3, y = 3
Output: 0
💡 Note: x = 3 (binary: 11), y = 3 (binary: 11). No bits differ, so Hamming distance = 0
Example 3 — Adjacent Numbers
$ Input: x = 7, y = 8
Output: 4
💡 Note: x = 7 (binary: 0111), y = 8 (binary: 1000). All 4 bit positions differ, so Hamming distance = 4

Constraints

  • 0 ≤ x, y ≤ 231 - 1

Visualization

Tap to expand
Hamming Distance - Brian Kernighan's Algorithm INPUT Two integers x and y x = 1 y = 4 Binary Representation x = 1: 0 0 1 y = 4: 1 0 0 XOR: 1 0 1 1 XOR 4 = 5 (binary: 101) Different bits highlighted xor = x ^ y = 5 ALGORITHM STEPS 1 XOR the numbers xor = 1 ^ 4 = 5 2 Initialize count = 0 Counter for set bits 3 While xor != 0 xor = xor & (xor-1) count++ 4 Return count Hamming distance Iterations: Iter 1: xor=5 (101) 5 & 4 = 4, count=1 Iter 2: xor=4 (100) 4 & 3 = 0, count=2 xor=0, loop ends FINAL RESULT Comparing bit positions: Pos: 2 1 0 x=1: 0 0 1 y=4: 1 0 0 ! ! Hamming Distance 2 OK - Verified! 2 bit positions differ between 1 and 4 Key Insight: Brian Kernighan's Algorithm: n & (n-1) clears the rightmost set bit. Each iteration removes exactly one set bit, so the number of iterations equals the number of 1s in the binary representation. Time Complexity: O(k) where k = number of set bits in XOR result. Much faster than O(log n)! TutorialsPoint - Hamming Distance | Brian Kernighan's Algorithm
Asked in
Facebook 15 Google 12
125.0K Views
Medium Frequency
~10 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen