Talentd
FleetCode
Make and follow sheets.Sign in

Hamming Distance solution and explanation

EasyBit Manipulation4 min read76.7% acceptanceUpdated 9 Apr 2026
Hamming Distance | LeetCode 461 | C++, Java, PythonKnowledge Center · 6:25 · 15K viewsWatch on YouTube
9 more videos on this problem
  1. Hamming Distance | LeetCode 461 | C++, Java, PythonKnowledge Center · 6:25 · 15K views
  2. Hamming Distance | Leetcode #461Techdose · 4:51 · 2K views
  3. Hamming Distance | LeetCode 461 | Programming TutorialsProgramming Tutorials · 5:45 · 2K views
  4. Hamming Distance | Leetcode 461 | Live coding session 🔥🔥🔥Coding Decoded · 4:36 · 1K views
  5. 461. Hamming Distance | LEETCODE EASY | BITS MANIPULATIONcode Explainer · 5:29 · 969 views
  6. Hamming Distance - LeetCode Problem #461GuyWho LikesCS · 14:45 · 821 views
  7. 461 Hamming Distance leetcode | two integers in which the corresponding bits are different - xor(^)Programmers Zone · 12:48 · 673 views
  8. LeetCode 461 Hamming DistanceTiny Tech Tales · 3:08 · 204 views
  9. Daily Leetcode #96: Jul 05, 2020 - 461. Hamming DistanceProgramming Live with Larry · 4:27 · 160 views
  10. Daily Leetcode #598: Nov 19, 2021 - 461. Hamming DistanceProgramming Live with Larry · 4:34 · 153 views

The 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 1:

Input: x = 1, y = 4
Output: 2
Explanation:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑
The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1
Output: 1

Constraints:

  • 0 <= x, y <= 231 - 1

Note: This question is the same as 2220: Minimum Bit Flips to Convert Number.

Approach overview

Problem Overview: Hamming Distance measures how many bit positions differ between two integers. Given two numbers x and y, return the number of positions where their binary representations contain different bits.

Approach 1: XOR + Bit Counting (O(1) time, O(1) space)

The key observation is that the XOR operation highlights differing bits. When you compute x ^ y, every bit position where x and y differ becomes 1, and matching positions become 0. The task then reduces to counting how many 1 bits exist in the XOR result. You can iterate through the bits using bit shifts and check the least significant bit with num & 1, or use built‑in population count functions available in most languages. Since integers have a fixed bit width (usually 32 or 64 bits), the runtime is effectively constant.

This approach directly applies bit manipulation techniques. It is simple, efficient, and the most commonly expected answer during interviews. The algorithm performs one XOR operation followed by a small loop over the bits, making it both readable and optimal.

Approach 2: XOR + Brian Kernighan’s Bit Trick (O(k) time, O(1) space)

Instead of checking every bit, you can repeatedly remove the lowest set bit using the expression n = n & (n - 1). Each iteration clears one 1 from the XOR result. Count how many times this operation runs until the number becomes zero. The loop executes exactly once for each set bit, so the runtime is O(k), where k is the number of differing bits.

This technique is a classic optimization in bit manipulation and relies on properties of bitwise operations. It avoids scanning all 32 bits and becomes faster when the XOR result contains only a few set bits.

Recommended for interviews: Start with the XOR insight. Interviewers expect you to recognize that differing bits correspond to 1s in x ^ y. A straightforward bit count already achieves optimal constant time. Mentioning Brian Kernighan’s trick shows deeper familiarity with bit manipulation patterns and often earns extra points. Both approaches use O(1) space and operate within the fixed integer bit width.

Approach 1: Using XOR and Bit Manipulation

To calculate the Hamming distance between two numbers, the most efficient way is to use the XOR operation. The result of XOR operation between two numbers highlights the bits that are different. Once you have the XOR result, the task reduces to counting the number of 1s in the binary representation of this number, which indicates the number of differing bits, thus giving the Hamming distance.

def hammingDistance(x, y):
    return bin(x ^ y).count('1')

x = 1
y = 4
print(hammingDistance(x, y))
public class HammingDistance {
    public static int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int count = 0;
        while (xor != 0) {
            count += xor & 1;
            xor >>= 1;
        }
        return count;
    }

    public static void main(String[] args) {
        int x = 1, y = 4;
        System.out.println(hammingDistance(x, y));
    }
}
#include <iostream>
using namespace std;

int hammingDistance(int x, int y) {
    int xor = x ^ y;
    int count = 0;
    while(xor != 0) {
        count += xor & 1;
        xor >>= 1;
    }
    return count;
}

int main() {
    int x = 1, y = 4;
    cout << hammingDistance(x, y) << endl;
    return 0;
}
function hammingDistance(x, y) {
    let xor = x ^ y;
    let count = 0;
    while (xor !== 0) {
        count += xor & 1;
        xor >>= 1;
    }
    return count;
}

console.log(hammingDistance(1, 4));
#include <stdio.h>

int hammingDistance(int x, int y) {
    int xor = x ^ y;
    int count = 0;
    while(xor != 0) {
        count += xor & 1;
        xor >>= 1;
    }
    return count;
}

int main() {
    int x = 1, y = 4;
    printf("%d\n", hammingDistance(x, y));
    return 0;
}
using System;

class HammingDistance {
    public static int Calculate(int x, int y) {
        int xor = x ^ y;
        int count = 0;
        while (xor != 0) {
            count += xor & 1;
            xor >>= 1;
        }
        return count;
    }

    static void Main() {
        int x = 1, y = 4;
        Console.WriteLine(Calculate(x, y));
    }
}

We use Python's bin() to convert the XOR result to a binary string and count('1') to count differing bits easily.

Complexity

Time Complexity: O(1) since integer size is constant.
Space Complexity: O(1) as space usage is constant.

Try this approach in the editor

Approach 2: Default Approach

function hammingDistance(x: number, y: number): number {
    x ^= y;
    let ans = 0;
    while (x) {
        x -= x & -x;
        ++ans;
    }
    return ans;
}
func hammingDistance(x int, y int) int {
	return bits.OnesCount(uint(x ^ y))
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Using XOR and Bit Manipulation

Time Complexity: O(1) since integer size is constant.
Space Complexity: O(1) as space usage is constant.

Default Approach–

Complexity analysis

ApproachTimeSpaceWhen to Use
XOR + Bit CountingO(1)O(1)General case. Simple and readable solution using XOR and counting set bits.
XOR + Brian Kernighan’s AlgorithmO(k)O(1)When the XOR result has few set bits. Efficient bit trick that removes one set bit per iteration.

Frequently asked questions

Is Hamming Distance easy or hard?

Hamming Distance is classified as an Easy problem. The main insight is recognizing that XOR reveals differing bit positions. Once that idea is clear, counting set bits completes the solution in a few lines of code.

Hamming Distance Python/Java solution

In Python, compute x ^ y and count set bits using bin(x ^ y).count('1') or bit operations. In Java, use Integer.bitCount(x ^ y). Both approaches run in constant time with O(1) space and rely on built-in bit counting utilities.

How to solve Hamming Distance in O(1)?

Compute x ^ y to identify the differing bit positions, then count the number of 1s in the result. Because integer size is fixed, the bit counting step runs in constant time. Many languages also provide built-in functions like popcount to compute the result efficiently.

What is the best approach for Hamming Distance?

The optimal approach uses XOR followed by counting the number of set bits. XOR highlights exactly the positions where two integers differ, turning the problem into a population count task. This solution runs in O(1) time because integers have a fixed bit width and uses O(1) extra space.

Is Hamming Distance asked at Google/Amazon/Meta?

Hamming Distance appears frequently in coding interviews at companies that test bit manipulation fundamentals. Variants or related questions have been reported in interviews at companies such as Amazon, Google, and Meta because they test understanding of XOR and bit counting techniques.

What data structure is used in Hamming Distance?

No specialized data structure is required. The solution relies on bitwise operations such as XOR, AND, and bit shifting. These operations are part of standard integer manipulation and fall under the bit manipulation category.

What is the time complexity of Hamming Distance?

Using the XOR approach, the time complexity is O(1) because at most 32 or 64 bits are processed depending on the integer type. If Brian Kernighan’s algorithm is used, the runtime becomes O(k), where k is the number of differing bits. Space complexity remains O(1).

Comments

Now write it yourselfClose this page and solve Hamming Distance in the editor, without looking.
Practise Hamming Distance