Hamming Distance is one of the simplest ways to measure the difference between two sequences. For two strings, arrays, or bit sequences of equal length, the Hamming Distance is the number of positions at which the corresponding values are different.
Despite its simplicity, it appears in algorithms, coding theory, networking, error detection, binary feature comparison, and some machine-learning problems.
The core idea
Consider these two strings:
karolin
kathrin
Compare them position by position:
k a r o l i n
k a t h r i n
↑ ↑ ↑
There are three different positions, so:
Hamming Distance = 3
The classical definition assumes that both sequences have the same length.
Formal definition
For two equal-length sequences x and y of length n:
H(x, y) = Σ [x[i] ≠ y[i]]
Each position contributes 1 if the values differ and 0 otherwise.
Example:
x = 1011101
y = 1001001
Comparison:
1 0 1 1 1 0 1
1 0 0 1 0 0 1
↑ ↑
Therefore:
H(x, y) = 2
How does the algorithm work?
The algorithm is straightforward:
- Verify that both inputs have the same length.
- Initialize a counter to zero.
- Scan both sequences from left to right.
- Increment the counter whenever corresponding values differ.
- Return the counter.
Pseudocode:
function hammingDistance(a, b):
if length(a) != length(b):
error
distance = 0
for i from 0 to length(a) - 1:
if a[i] != b[i]:
distance++
return distance
TypeScript implementation
function hammingDistance(a: string, b: string): number {
if (a.length !== b.length) {
throw new Error("Inputs must have the same length.");
}
let distance = 0;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {
distance++;
}
}
return distance;
}
console.log(hammingDistance("karolin", "kathrin")); // 3
The implementation makes one pass over the input and uses constant extra space.
Time and space complexity
For inputs of length n:
Time Complexity: O(n)
Space Complexity: O(1)
Every position has to be inspected at least once in the general case, so linear time is optimal for the standard sequence version.
Hamming Distance for binary integers
A common variation compares the bits of two integers.
Suppose:
x = 10 -> 1010
y = 14 -> 1110
Only one bit differs:
1010
1110
↑
Therefore the distance is 1.
For integers, XOR gives a very convenient solution:
1010
XOR
1110
----
0100
Every 1 in the XOR result represents one position where the original numbers differed.
So:
Hamming Distance = number of set bits in (x XOR y)
TypeScript example:
function hammingDistanceBits(x: number, y: number): number {
let value = x ^ y;
let distance = 0;
while (value !== 0) {
distance += value & 1;
value >>>= 1;
}
return distance;
}
Faster set-bit counting
Brian Kernighan's bit trick removes one set bit at each iteration:
function hammingDistanceBits(x: number, y: number): number {
let value = x ^ y;
let distance = 0;
while (value !== 0) {
value &= value - 1;
distance++;
}
return distance;
}
The expression:
value & (value - 1)
clears the least-significant set bit.
Real-world applications
1. Error detection and coding theory
Hamming Distance is fundamental to error-detecting and error-correcting codes. The distance between valid code words determines how many transmission errors can be detected or corrected.
2. Binary code comparison
Digital systems frequently need to compare bit patterns. Hamming Distance provides a direct measure of how many bits differ.
3. Networking and communication
Some communication techniques use Hamming-related ideas to detect corruption in transmitted data.
4. Image processing and binary descriptors
Computer-vision systems can represent local image features as binary descriptors. Hamming Distance is useful because those descriptors can be compared quickly.
5. Machine learning and binary features
For categorical or binary feature vectors, Hamming Distance can act as a simple distance measure.
Example:
User A = [1, 0, 1, 1, 0]
User B = [1, 1, 1, 0, 0]
The Hamming Distance is 2.
Hamming Distance vs. Levenshtein Distance
These two concepts are often confused.
Hamming Distance compares corresponding positions and normally requires equal-length inputs.
Levenshtein Distance allows three edit operations:
- Insert
- Delete
- Replace
For:
cat
cut
both distances are 1.
But for:
cat
cats
classical Hamming Distance is not defined because the lengths differ, while Levenshtein Distance is 1.
When should you use Hamming Distance?
Use it when:
- The sequences have equal length.
- Position matters.
- You only care about substitutions or mismatches.
- You are comparing binary data.
- You want a simple and fast distance measure.
If insertions and deletions must be taken into account, a metric such as Levenshtein Distance is usually more appropriate.
A common interview problem
A typical question is:
Given two integers
xandy, calculate how many bits must change to transformxintoy.
The solution is:
1. Compute x XOR y.
2. Count the set bits in the result.
Example:
x = 1 -> 0001
y = 4 -> 0100
XOR -> 0101
Two bits are set, so:
Hamming Distance = 2
Common mistakes
A common mistake is applying Hamming Distance to inputs of different lengths without defining a custom rule.
Another is assuming that it can identify insertion, deletion, or shifted characters. It cannot; it compares corresponding positions only.
For integer bit problems, using XOR first is generally the cleanest approach.
Conclusion
Hamming Distance is simple, but it represents an important idea in computer science:
It counts the positions at which two equal-length sequences differ.
For strings, it can be implemented with a single loop. For binary integers, the standard pattern is XOR + set-bit counting.
Its O(n) sequence complexity, constant extra space, and natural fit for binary data make it useful in algorithms, coding theory, networking, data processing, computer vision, and technical interviews.