MEDIUM Bit Manipulation

461. 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.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation

๐Ÿ’ก Approach

  • โ†’ XOR x and y: set bits are positions where they differ
  • โ†’ Count the number of set bits in the XOR result
  • โ†’ Time: O(1) - max 32 iterations for 32-bit integers, Space: O(1)
  • โ†’ in popcount, Brian Kernighan's algorithm

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขXOR x and y: set bits are positions where they differ
  • โ€ขCount the number of set bits in the XOR result
  • โ€ขTime: O(1) - max 32 iterations for 32-bit integers, Space: O(1)

Common Pitfalls

  • โ€ขin popcount, Brian Kernighan's algorithm

๐Ÿงช Test Cases

Hidden tests on submit: 1

Test Case 1
Not run
Input:
hammingDistance(1, 4);
Expected:
2
Test Case 2
Not run
Input:
hammingDistance(3, 1);
Expected:
1
Test Case 3
Not run
Input:
hammingDistance(0, 0);
Expected:
0

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit