Arian Soleimanzadeh
  • Home
  • Blog
  • Podcasts
  • Videos
  • Contact
العربيةArabic
DeutschGerman
EnglishEnglish
فارسیPersian
한국어Korean
中文Chinese
Panel•Quick Contact

Languages

Choose your interface locale

ar

العربية

Arabic

de

Deutsch

German

en

English

English

fa

فارسی

Persian

ko

한국어

Korean

zh

中文

Chinese

Get Appointment

Drop a quick message — I’ll reply as soon as possible.

LinkedInFast response
Home/Articles/What Is Hamming Distance? From the Core Idea to Implementation and Real-World Uses
AlgorithmsArticle

What Is Hamming Distance? From the Core Idea to Implementation and Real-World Uses

Hamming Distance is a simple and efficient way to measure how many positions differ between two equal-length sequences. This guide covers the concept, implementation, complexity, binary optimization, and practical applications.

August 19, 20267 min read1 Views
#Algorithms#Hamming Distance#String Algorithms#Bit Manipulation#TypeScript#Computer Science

Arian Soleimanzadeh

Software Engineer & Researcher

Conceptual visualization of the Hamming Distance algorithm comparing strings and binary bits

Arian Soleimanzadeh

AI · Code · Product

Research + Engineering
On this page
The core ideaFormal definitionHow does the algorithm work?TypeScript implementationTime and space complexityHamming Distance for binary integersFaster set-bit countingReal-world applications1. Error detection and coding theory2. Binary code comparison3. Networking and communication4. Image processing and binary descriptors5. Machine learning and binary featuresHamming Distance vs. Levenshtein DistanceWhen should you use Hamming Distance?A common interview problemCommon mistakesConclusion

Hamming Distance is one of the simplest ways to measure the difference between two sequences. For two strings, arrays, or bit sequences of equal length, the Hamming Distance is the number of positions at which the corresponding values are different.

Despite its simplicity, it appears in algorithms, coding theory, networking, error detection, binary feature comparison, and some machine-learning problems.


The core idea

Consider these two strings:

karolin
kathrin

Compare them position by position:

k a r o l i n
k a t h r i n
    ↑ ↑ ↑

There are three different positions, so:

Hamming Distance = 3

The classical definition assumes that both sequences have the same length.


Formal definition

For two equal-length sequences x and y of length n:

H(x, y) = Σ [x[i] ≠ y[i]]

Each position contributes 1 if the values differ and 0 otherwise.

Example:

x = 1011101
y = 1001001

Comparison:

1 0 1 1 1 0 1
1 0 0 1 0 0 1
    ↑   ↑

Therefore:

H(x, y) = 2

How does the algorithm work?

The algorithm is straightforward:

  1. Verify that both inputs have the same length.
  2. Initialize a counter to zero.
  3. Scan both sequences from left to right.
  4. Increment the counter whenever corresponding values differ.
  5. Return the counter.

Pseudocode:

function hammingDistance(a, b):
    if length(a) != length(b):
        error

    distance = 0

    for i from 0 to length(a) - 1:
        if a[i] != b[i]:
            distance++

    return distance

TypeScript implementation

function hammingDistance(a: string, b: string): number {
  if (a.length !== b.length) {
    throw new Error("Inputs must have the same length.");
  }

  let distance = 0;

  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      distance++;
    }
  }

  return distance;
}

console.log(hammingDistance("karolin", "kathrin")); // 3

The implementation makes one pass over the input and uses constant extra space.


Time and space complexity

For inputs of length n:

Time Complexity: O(n)
Space Complexity: O(1)

Every position has to be inspected at least once in the general case, so linear time is optimal for the standard sequence version.


Hamming Distance for binary integers

A common variation compares the bits of two integers.

Suppose:

x = 10  -> 1010
y = 14  -> 1110

Only one bit differs:

1010
1110
 ↑

Therefore the distance is 1.

For integers, XOR gives a very convenient solution:

1010
XOR
1110
----
0100

Every 1 in the XOR result represents one position where the original numbers differed.

So:

Hamming Distance = number of set bits in (x XOR y)

TypeScript example:

function hammingDistanceBits(x: number, y: number): number {
  let value = x ^ y;
  let distance = 0;

  while (value !== 0) {
    distance += value & 1;
    value >>>= 1;
  }

  return distance;
}

Faster set-bit counting

Brian Kernighan's bit trick removes one set bit at each iteration:

function hammingDistanceBits(x: number, y: number): number {
  let value = x ^ y;
  let distance = 0;

  while (value !== 0) {
    value &= value - 1;
    distance++;
  }

  return distance;
}

The expression:

value & (value - 1)

clears the least-significant set bit.


Real-world applications

1. Error detection and coding theory

Hamming Distance is fundamental to error-detecting and error-correcting codes. The distance between valid code words determines how many transmission errors can be detected or corrected.

2. Binary code comparison

Digital systems frequently need to compare bit patterns. Hamming Distance provides a direct measure of how many bits differ.

3. Networking and communication

Some communication techniques use Hamming-related ideas to detect corruption in transmitted data.

4. Image processing and binary descriptors

Computer-vision systems can represent local image features as binary descriptors. Hamming Distance is useful because those descriptors can be compared quickly.

5. Machine learning and binary features

For categorical or binary feature vectors, Hamming Distance can act as a simple distance measure.

Example:

User A = [1, 0, 1, 1, 0]
User B = [1, 1, 1, 0, 0]

The Hamming Distance is 2.


Hamming Distance vs. Levenshtein Distance

These two concepts are often confused.

Hamming Distance compares corresponding positions and normally requires equal-length inputs.

Levenshtein Distance allows three edit operations:

  • Insert
  • Delete
  • Replace

For:

cat
cut

both distances are 1.

But for:

cat
cats

classical Hamming Distance is not defined because the lengths differ, while Levenshtein Distance is 1.


When should you use Hamming Distance?

Use it when:

  • The sequences have equal length.
  • Position matters.
  • You only care about substitutions or mismatches.
  • You are comparing binary data.
  • You want a simple and fast distance measure.

If insertions and deletions must be taken into account, a metric such as Levenshtein Distance is usually more appropriate.


A common interview problem

A typical question is:

Given two integers x and y, calculate how many bits must change to transform x into y.

The solution is:

1. Compute x XOR y.
2. Count the set bits in the result.

Example:

x = 1  -> 0001
y = 4  -> 0100

XOR     -> 0101

Two bits are set, so:

Hamming Distance = 2

Common mistakes

A common mistake is applying Hamming Distance to inputs of different lengths without defining a custom rule.

Another is assuming that it can identify insertion, deletion, or shifted characters. It cannot; it compares corresponding positions only.

For integer bit problems, using XOR first is generally the cleanest approach.


Conclusion

Hamming Distance is simple, but it represents an important idea in computer science:

It counts the positions at which two equal-length sequences differ.

For strings, it can be implemented with a single loop. For binary integers, the standard pattern is XOR + set-bit counting.

Its O(n) sequence complexity, constant extra space, and natural fit for binary data make it useful in algorithms, coding theory, networking, data processing, computer vision, and technical interviews.

On this page
The core ideaFormal definitionHow does the algorithm work?TypeScript implementationTime and space complexityHamming Distance for binary integersFaster set-bit countingReal-world applications1. Error detection and coding theory2. Binary code comparison3. Networking and communication4. Image processing and binary descriptors5. Machine learning and binary featuresHamming Distance vs. Levenshtein DistanceWhen should you use Hamming Distance?A common interview problemCommon mistakesConclusion

Article details

Publication metadata, reading time and live view information.

Published

August 19, 2026

Updated

August 19, 2026

Reading time

7 min read

Views

1

Author

Arian Soleimanzadeh

Previous article

B2B CRM vs. B2C CRM: From Sales Processes to Software Architecture

Next article

What Is the KMP Algorithm? Fast String Searching with Knuth–Morris–Pratt

Let’s build something clean, fast, and beautiful.

Quick contact for collaborations, consulting, or product work.

Quick ContactEmail Me
Arian Soleimanzadeh

Personal portfolio focused on modern web engineering, UI systems, and practical AI products — clean code, clean design.

Quick Links

  • About
  • Blog
  • Projects
  • Contact

Contact

  • info@ariansoleimanzadeh.site
  • soleimanzadeh.a.work@gmail.com

Availability: Weekdays

Typically replies within 24h.

Newsletter

Get updates on posts, projects, and new releases.

© 2026 ariansoleimanzadeh.site — All rights reserved.

LinkedIn