Sub topic 3
A Simpler Cousin: Hamming Distance for Equal-Length Strings
This chapter assumes you can write basic Python and know Big-O notation. It also assumes you have read the previous chapter, which defined Levenshtein distance as the minimum number of insertions, deletions, and substitutions needed to turn one string into another. Here we remove two of those three operations and see what is left.
Hamming distance is the number of positions at which two equal-length strings have different characters. It is edit distance restricted to substitutions only. Since there is no way to insert or delete, the strings must already have the same length, and position i in one string can only ever be compared with position i in the other.
The Definition
For two strings a and b of the same length n:
- Hamming(a, b) = the count of indices
iwith0 <= i < nanda[i] != b[i]. - If
len(a) != len(b), Hamming distance is undefined.
Take karolin and kathrin:
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| a | k | a | r | o | l | i | n |
| b | k | a | t | h | r | i | n |
| Differs? | no | no | yes | yes | yes | no | no |
Three positions differ, so the Hamming distance is 3. Each mismatch costs one substitution, and the alignment is fixed, so nothing needs to be optimized. You read the answer off by scanning once.
A Reference Implementation
def hamming(a, b):
if len(a) != len(b):
raise ValueError("Hamming distance requires equal-length strings")
return sum(x != y for x, y in zip(a, b))
assert hamming("karolin", "kathrin") == 3
assert hamming("", "") == 0
assert hamming("abc", "abc") == 0
print(hamming("karolin", "kathrin"))The expression x != y produces a boolean, and Python treats True as 1 when summing, so sum counts the mismatches. The function runs in O(n) time and O(1) extra space. It needs no table and no recurrence, which is the main contrast with the dynamic programming chapters that follow.
How Hamming Relates to Levenshtein
When the lengths are equal, both distances are defined, and they are related by a simple inequality:
- Levenshtein(a, b) <= Hamming(a, b).
The reason is that substituting every mismatched position is one valid sequence of edits. It uses exactly Hamming(a, b) operations. Levenshtein distance is the minimum over all valid edit sequences, so it can never exceed this one.
The gap can be large. Compare abcdef with fabcde, which is the same string rotated one place to the right:
| Position | 0 | 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|---|---|
| a | a | b | c | d | e | f |
| b | f | a | b | c | d | e |
| Differs? | yes | yes | yes | yes | yes | yes |
Every position differs, so Hamming distance is 6. Levenshtein distance is only 2: insert f at the front and delete the trailing f. A single shifted character puts every later position out of alignment, and Hamming distance has no way to realign them. This is the defining weakness of Hamming distance: it measures substitution errors well and shifts badly.
| Property | Hamming | Levenshtein |
|---|---|---|
| Operations allowed | Substitution | Insertion, deletion, substitution |
| Input lengths | Must be equal | Any |
| Alignment | Fixed, position by position | Chosen to minimize cost |
| Time | O(n) | O(mn) with the standard algorithm |
| Extra space | O(1) | O(mn) for the full table, less with tricks |
| Sensitive to shifts | Very | No |
Hamming Distance on Bits
Hamming distance originated in coding theory, where the strings are binary codewords. For integers, there is a fast idiom: XOR the two values, then count the 1 bits. A bit in x ^ y is 1 exactly where x and y differ.
def hamming_bits(x, y):
return bin(x ^ y).count("1")
assert hamming_bits(0b1011101, 0b1001001) == 2
assert hamming_bits(0, 0) == 0
assert hamming_bits(0b1111, 0b0000) == 4
print(hamming_bits(0b1011101, 0b1001001))On Python 3.10 and later, (x ^ y).bit_count() does the same thing without building a string. In C, C++, and Rust, the population count compiles to a single CPU instruction on most modern hardware, so comparing 64-bit fingerprints takes a few nanoseconds. This speed is why Hamming distance is used for comparing perceptual image hashes, SimHash document fingerprints, and binary feature descriptors in computer vision.
In coding theory, the minimum Hamming distance d between any two codewords in a code sets its error-handling ability. Such a code can detect up to d - 1 flipped bits and correct up to (d - 1) // 2 of them. These guarantees rely on the channel only flipping bits. If the channel can also drop or insert bits, Hamming-based guarantees no longer apply, and you need insertion/deletion-aware codes.
Where Hamming Distance Fits
Use Hamming distance when the data has a fixed layout and errors are substitutions:
- Fixed-length identifiers and codes, such as comparing two barcodes or checksums of the same format.
- DNA sequencing reads where the technology mostly produces substitution errors and the reads are already aligned to a reference.
- Binary hashes and fingerprints of fixed width.
- Comparing two equal-length time slots, such as positions in a fixed schedule.
Do not use it for typed text, spell checking, or diffing files. Human typing errors include missing and extra characters, and one dropped letter early in a word inflates the Hamming distance for everything after it.
Common Errors
Silent truncation with `zip`
The most frequent bug is writing the one-liner without the length check:
def hamming_buggy(a, b):
return sum(x != y for x, y in zip(a, b))
print(hamming_buggy("abc", "abcdef")) # prints 0, which is wrongzip stops at the shorter input, so the extra characters are ignored and two clearly different strings get distance 0. On Python 3.10 and later, zip(a, b, strict=True) raises ValueError when the lengths differ. Either use that or check the lengths explicitly.
Unicode length mismatches
Two strings that look identical can have different lengths in Python. The letter é can be one code point (U+00E9) or two (e followed by a combining acute accent, U+0301). Normalize before comparing:
import unicodedata
def hamming(a, b):
if len(a) != len(b):
raise ValueError("Hamming distance requires equal-length strings")
return sum(x != y for x, y in zip(a, b))
composed = "caf\u00e9"
decomposed = "cafe\u0301"
print(len(composed), len(decomposed)) # 4 5
a = unicodedata.normalize("NFC", composed)
b = unicodedata.normalize("NFC", decomposed)
print(hamming(a, b)) # 0The same issue affects Levenshtein distance, but Hamming distance hits it harder: without normalization it refuses to compute anything at all.
Case and formatting
"ABC" and "abc" have Hamming distance 3. If case should not matter, apply casefold() to both strings first. The same applies to stray whitespace or formatting characters in identifiers. Decide what counts as "the same character" before measuring.
Summary of the Model
Hamming distance fixes the alignment and counts mismatches. That makes it cheap and simple, and it is an upper bound on Levenshtein distance whenever both are defined. The cost of the fixed alignment is that one insertion or deletion can push the distance up to nearly the full string length. The rest of this tutorial covers how Levenshtein distance chooses the best alignment, and what that choice costs.
Exercise
Compute the Hamming distance between "toned" and "roses", and list the differing positions (0-indexed).
Show answer
Positions 0 (t/r), 2 (n/s), and 4 (d/s) differ; positions 1 (o) and 3 (e) match. The Hamming distance is 3.
Exercise
Find two strings of length 4 whose Hamming distance is 4 but whose Levenshtein distance is 2, and give the two edits.
Show answer
"abcd" and "bcda". Every position differs, so Hamming distance is 4. Delete the leading "a" to get "bcd", then insert "a" at the end to get "bcda": Levenshtein distance is 2. Any one-place rotation of a string with no repeated adjacent pattern works the same way.
Exercise
Explain why Levenshtein(a, b) can never be greater than Hamming(a, b) when len(a) == len(b), and say when the two are equal.
Show answer
Substituting each mismatched position is a valid edit sequence of length Hamming(a, b), and Levenshtein distance is the minimum over all edit sequences, so it is at most that value. They are equal when no combination of insertions and deletions beats plain substitution. For example, Hamming distance 0 or 1 always matches Levenshtein, and so does "karolin" versus "kathrin" (both 3).
Exercise
A colleague computes the Hamming distance between the 64-bit perceptual hashes 0xFF00 and 0x0FF0 with bin(x ^ y).count("1"). What result do they get, and why is this approach appropriate here?
Show answer
0xFF00 ^ 0x0FF0 = 0xF0F0, which has 8 one-bits, so the distance is 8. The approach fits because the hashes have a fixed width and each bit position has a fixed meaning, so differences are bit flips (substitutions) and nothing ever shifts.