Skip to content
DSA in JavaScript
Advanced Strings & DP

Hamming Distance

Algorithm · Stretch

Level: StretchString Matching

Step through it: String Matching pattern

text
a
b
a
b
c
a
b
pattern
a
b
c

Step 1 of 5

Goal: find "abc" inside "ababcab". Slide the pattern along the text and compare letter by letter.

the Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. In other words, it measures the minimum number of substitutions required to change one string into the other, or the minimum number of errors that could have transformed one string into the other. In a more general context, the Hamming distance is one of several string metrics for measuring the edit distance between two sequences.

Examples

The Hamming distance between:

  • "karolin" and "kathrin" is 3.
  • "karolin" and "kerstin" is 3.
  • 1011101 and 1001001 is 2.
  • 2173896 and 2233796 is 3.

Code

hammingDistance.js
/**
 * @param {string} a
 * @param {string} b
 * @return {number}
 */
export default function hammingDistance(a, b) {
  if (a.length !== b.length) {
    throw new Error('Strings must be of the same length');
  }

  let distance = 0;

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

  return distance;
}

References

Wikipedia

Practice

Spotted a mistake or something unclear? Report it on GitHub.

On this page