Computer Science
Advanced

Hamming Distance

Number of positions at which two strings differ.

Formula

d(x,y)=∑i[xi≠yi]d(x,y) = \sum_i [x_i \ne y_i]

Variables

x, yEqual-length strings

Example

1011 vs 1001 differ in one bit, so their Hamming distance is 1.

How it works

Hamming distance counts how many coordinates in two equal-length strings disagree, so it is a direct measure of how many symbol changes are needed to turn one string into the other. The indicator [x_i \ne y_i] equals 1 exactly when the symbols differ and 0 otherwise, and summing over all positions adds up those mismatches. This makes it useful as a metric on binary strings, codes, and any fixed-length symbol sequences where only position-by-position comparison matters.

When to use it

Use Hamming distance when comparing equal-length bitstrings, DNA bases, fixed-length labels, or encoded messages to measure error, similarity, or decoding effort. It is especially common in coding theory, cryptography, and machine learning tasks involving categorical vectors.

Worked example, step by step

Let x = 1100101 and y = 1001100. Compare each position: 1 vs 1 -> same, contributes 0 1 vs 0 -> different, contributes 1 0 vs 0 -> same, contributes 0 0 vs 1 -> different, contributes 1 1 vs 1 -> same, contributes 0 0 vs 0 -> same, contributes 0 1 vs 0 -> different, contributes 1 Sum the contributions: d(x,y) = 0 + 1 + 0 + 1 + 0 + 0 + 1 = 3 Final answer: the Hamming distance is 3.

Common mistakes to avoid

  • Using strings of different lengths without aligning or padding them first
  • Counting how many 1s or 0s appear instead of how many positions differ
  • Treating transpositions or reordered characters as one mismatch per swap rather than comparing positions directly

Did You Know?

Hamming distance measures how many bits differ — the basis of error-correcting codes in CDs and deep-space probes.

Share this formula

Reviewed & maintained by the FormulaWon editorial teamLast reviewed September 2026