Python 0461.py
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return (x ^ y).bit_count()
Difficulty
and has an acceptance rate of about 77% (800k+ submissions).
Typical patterns to solve this problem:
- Bit Manipulation
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation defines a Solution class with a single method hammingDistance. The method computes the Hamming distance between two integers x and y by applying a bitwise exclusive-or (XOR) operation followed by a built-in population count. The entire computation is expressed in a single return statement, leveraging Python’s native integer handling and optimized C-level primitives.
Key Steps
The core logic consists of two distinct operations that are combined into one expression.
XOR Computation
x ^ y
The XOR operator produces a new integer whose binary representation has a 1 in each position where the corresponding bits of x and y differ. This step isolates exactly the bits that contribute to the Hamming distance.
Population Count
(...).bit_count()
The bit_count method, introduced in Python 3.8, returns the number of set bits (1s) in the binary representation of its operand. By invoking it on the result of the XOR, the method directly yields the count of differing bit positions, which is the definition of Hamming distance.
Edge Cases Handled
When both inputs are identical, the XOR yields zero; 0.bit_count() correctly returns 0, indicating no differing bits. The implementation also gracefully handles the case where either operand is zero; the XOR reduces to the other operand, and bit_count counts the set bits of that operand. Python’s arbitrary-precision integers mean that very large values, far exceeding typical 32- or 64-bit limits, are processed without overflow or truncation. Negative integers are accepted as well; bit_count operates on the absolute value of the integer, ensuring that the count reflects the number of 1s in the magnitude’s binary form, which aligns with the mathematical interpretation of Hamming distance for signed inputs.
Performance Optimizations
The solution relies entirely on built-in operations that are implemented in CPython’s C core. The XOR operation is a low-level bitwise primitive that executes in constant time relative to the word size of the underlying hardware. The bit_count method is also a native routine that uses highly optimized algorithms (such as hardware popcnt instructions when available) to count set bits efficiently. By avoiding explicit loops, conditionals, or intermediate data structures, the implementation minimizes Python-level overhead and benefits from the speed of compiled code paths. This results in a concise, fast, and memory-light computation of the Hamming distance.
ELI5 - Simplified Explanation
Imagine you have two treasure chests labeled with numbers. Inside each chest is a secret code made of bits, which are just tiny lights that are either on or off. This code looks at both chests at the same time and plays a game of spot the difference. It compares the lights one by one to see which ones are different. If one light is on in the first chest but off in the second, or if it is off in the first but on in the second, that counts as a mismatched light. After checking all of them, the code counts up exactly how many places did not match. It is like counting how many light switches you would need to flip to make both chests look exactly the same.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | ||||||||||
| www | AlgoMonster | C++ | Java | Python | TS | ||||||
| WalkCCC | C++ | Java | Python | ||||||||
| leetcode.ca | C++ | Java | Python | JS | Go | TS | |||||
| LeetcodeHelp | C++ | Java | Python | ||||||||
| Progiez | C++ | Java | Python | ||||||||
| github | BigEggStudy | C# | |||||||||
| black-shadows | C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JS | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JS | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| zfang399 | C++ | ||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||||
| WalkCCC | C++, Python, Java | ||||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python, TypeScript | ||||||||||
| LeetcodeHelp | C++, Java, Python | ||||||||||
| Progiez | C++, Java, Python | ||||||||||
| BigEggStudy | C# | ||||||||||
| black-shadows | C++, C++ | ||||||||||
| chandansgowda | Python | ||||||||||
| charles-wangkai | Java | ||||||||||
| DimitrisJim | C | ||||||||||
| everthis | JavaScript | ||||||||||
| fartem | Ruby | ||||||||||
| fengvyi | C++ | ||||||||||
| fpdjsns | C++ | ||||||||||
| fsq | C++ | ||||||||||
| gouthampradhan | Java | ||||||||||
| halfrost | Go | ||||||||||
| JoshCrozier | JavaScript | ||||||||||
| keineahnung2345 | C++ | ||||||||||
| Krazune | C++ | ||||||||||
| linouk23 | C++ | ||||||||||
| lkwq007 | Python | ||||||||||
| qiyuangong | Java | ||||||||||
| ruoru | Rust | ||||||||||
| suxrobGM | C# | ||||||||||
| varunu28 | Java | ||||||||||
| vli02 | C | ||||||||||
| vthwang | Java | ||||||||||
| zfang399 | C++ |
Videos
Similar Problems
- problem 191: Number of 1 Bits
- problem 477: Total Hamming Distance
Solved On The Same Day
- problem 263: Ugly Number
- problem 133: Clone Graph
- problem 142: Linked List Cycle II
- problem 143: Reorder List
- problem 264: Ugly Number II
- problem 313: Super Ugly Number
- problem 454: 4Sum II
- problem 477: Total Hamming Distance
- problem 10: Regular Expression Matching
Fun Facts
This is my highest quality solution (easy) with an average rating of 9.4.
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality