Problem 461

Abstract / Summary

The task is to calculate how many positions have different values between the binary forms of two given integers.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0461.py

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        return (x ^ y).bit_count()
3 lines | 108 bytes | submitted August 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 77% (800k+ submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 10 | μ = 9.41 | σ = 0.83

Complexity Analysis

not analyzed yet

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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++
43 links | 29 authors | 10 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

1 easy 7 medium 1 hard
10 solutions   August 19, 2023

Fun Facts

This is my highest quality solution (easy) with an average rating of 9.4.

1 fun fact

Extra

There are a few extra pages giving you some insights into my setup:
  • 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