Hamming Distance between two given strings

Objective: Given two strings with equal lengths, write an algorithm to calculate the hamming distance between the strings. 

Hamming Distance: Hamming distance between two strings is the number of positions at which the characters are different.

Example:

X = AABBCCDD, Y = AAAACCCC
Hamming distance: 4
There are four positions at which bits are different

X = dogandcat, Y = catanddog
Hamming distance: 6
There are six positions at which bits are different.

Approach:

  • Initialize humming_distance = 0.
  • Iterate both strings, one character at a time. If characters are different then increment humming_distance by 1. 
  • Once the iteration is completed, return the humming_distance.

Complete Code: 

Output:

x=AABBCCDD, y=AAAACCCC  Hamming distance: 4
x=dogandcat, y=catanddog  Hamming distance: 6

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

%d bloggers like this: