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
๐งญ Prerequisites
๐ ๏ธ 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
๐ค Output