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.


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.


  • 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:


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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: