Hamming Distance
Algorithm · Stretch
Step through it: String Matching pattern
Step 1 of 5
Goal: find "abc" inside "ababcab". Slide the pattern along the text and compare letter by letter.
Step 2 of 5
At position 0: a matches, b matches, then c meets a. Mismatch.
Step 3 of 5
The slow way starts over one step later and re-reads letters. Clever methods (KMP and friends) remember that "ab" already matched, so they jump ahead and never re-read the text.
Step 4 of 5
Match found at position 2. The work is about n + m instead of n × m. This family is string matching.
Step 5 of 5
Your turn.
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
/**
* @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
Practice
String Matching
- Find the Index of the First Occurrence in a StringEasy
- Repeated Substring PatternEasy
- Is SubsequenceEasy
- Rotate StringEasy
- Longest Palindromic SubstringMedium
- Palindromic SubstringsMedium
- Repeated String MatchMedium
- One Edit DistanceMedium
- Shortest PalindromeHard
- Longest Happy PrefixHard
- Longest Duplicate SubstringHard
- Edit DistanceHard
- Wildcard MatchingHard
Spotted a mistake or something unclear? Report it on GitHub.