The Hamming Distance algorithm is a very interesting question that you may have heard in your school or college asked in many interviews including FAANG companies.
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.
Example 1:
Input: a = karolin, b = kathrin
Output: 3
Example 2:
Input: a = 2173896, b = 2233796
Output: 3
Let's start with the algorithm,
var hammingDistance = function(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;
}
Here, we just compare characters from strings one by one when they are different we increment the distance by one.
I hope you understood the algorithm. If you have any doubts, please let us know in the comments.
0 Comments