Sub topic 12
When Is an Edit Distance a True Metric?
This chapter assumes you have read the earlier chapters on the Levenshtein recurrence, the DP table, weighted costs, and the OSA and Damerau-Levenshtein variants. You should be comfortable reading Python and following a short inductive argument.
Up to now, edit distance has been a number we compute. Many systems also reason with that number. They assume that if x is close to y and y is close to z, then x cannot be far from z. That assumption holds only when the distance is a metric. Some popular variants are not metrics, and code that assumes they are can silently return wrong results.
The Four Metric Axioms
A function d on strings is a metric when, for all strings x, y, and z, these four axioms hold:
| Axiom | Statement | What breaks if it fails |
|---|---|---|
| Non-negativity | `d(x, y) >= 0` | Costs could cancel out, so "distance" loses meaning |
| Identity of indiscernibles | `d(x, y) == 0` exactly when `x == y` | Different strings look identical |
| Symmetry | `d(x, y) == d(y, x)` | Results depend on argument order |
| Triangle inequality | `d(x, z) <= d(x, y) + d(y, z)` | Pruning by distance bounds misses true matches |
A function that satisfies all of these except identity is called a pseudometric: distinct strings may have distance 0. A function that is a metric in every way except symmetry is a quasimetric.
Why Levenshtein Distance Is a Metric
Each axiom follows from the definition as "the minimum number of operations".
- Non-negativity. Every operation costs 1, so any script costs at least 0.
- Identity. The empty script turns
xintox, sod(x, x) = 0. Ifx != y, at least one operation is needed, sod(x, y) >= 1. - Symmetry. Every operation has an inverse of equal cost. Inserting
cundoes deletingc, and substitutingbforaundoes substitutingaforb. Reverse a script fromxtoyand invert each step, and you get a script fromytoxof the same length. - Triangle inequality. Take an optimal script from
xtoyand an optimal script fromytoz. Run them back to back. The result is a valid script fromxtozwith costd(x, y) + d(y, z). The optimal script fromxtozcan only be cheaper.
The triangle-inequality argument has a subtle step. The DP table computes the cheapest alignment, in which each character takes part in at most one operation. The concatenated script may touch a character twice, for example substituting it and then substituting it again. For unit-cost Levenshtein this is harmless, because any script that edits a position twice can be shortened into an alignment that costs no more. So the DP value equals the minimum over all scripts, and the concatenation argument applies. The variants below run into trouble at exactly this step.
Hamming distance is also a metric on strings of a fixed length. The indel distance (insertions and deletions only, equal to m + n - 2 * LCS) is a metric too, by the same inverse-and-concatenate argument.
Where Variants Break the Axioms
Optimal String Alignment Violates the Triangle Inequality
OSA adds adjacent transpositions but forbids editing any substring more than once. That rule blocks the concatenation argument. Here is the classic counterexample:
osa("ca", "ac") = 1(one transposition)osa("ac", "abc") = 1(one insertion)osa("ca", "abc") = 3
The direct path costs 3, while the detour through "ac" costs 2. Reaching "abc" cheaply would mean transposing ca and then inserting b between the two characters you just swapped. OSA does not allow that. Unrestricted Damerau-Levenshtein allows it, gives d("ca", "abc") = 2, and is a true metric.
Asymmetric Weights Break Symmetry
If deletion costs 2 and insertion costs 1, then turning "a" into "" costs 2, but turning "" into "a" costs 1. The result is a quasimetric. The same thing happens when sub(a, b) != sub(b, a).
Zero Costs Break Identity
If substituting "0" for "O" costs 0 (a typical OCR-friendly choice), then d("C0DE", "CODE") = 0 although the strings differ. The result is a pseudometric. That may be exactly what you want, but metric data structures will then treat the two strings as the same point.
Badly Chosen Substitution Costs Break the Triangle Inequality
Weighted costs can break the triangle inequality even when they are positive and symmetric. Suppose sub(a, c) = 10, sub(a, b) = sub(b, c) = 1, and every insertion or deletion costs 10. The DP aligns "a" with "c" directly at cost 10, since deleting and re-inserting costs 20. The route through "b" costs only 2. The DP cannot "pass through" an intermediate character, because each position is edited once. The repair is to make the substitution costs satisfy the triangle inequality themselves, sub(a, c) <= sub(a, b) + sub(b, c), and likewise to keep sub(a, b) <= del(a) + ins(b).
Checking the Axioms by Brute Force
Proofs are best, but an exhaustive search over short strings is a cheap way to catch mistakes. The script below builds every string up to length 3 over {a, b, c}, precomputes all pairwise distances, and looks for a triangle violation. It also confirms the weighted counterexample from above.
from itertools import product
def levenshtein(a, b):
prev = list(range(len(b) + 1))
for i, ca in enumerate(a, 1):
curr = [i]
for j, cb in enumerate(b, 1):
curr.append(min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + (ca != cb)))
prev = curr
return prev[-1]
def osa_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else 1
dp[i][j] = min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost)
if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
dp[i][j] = min(dp[i][j], dp[i - 2][j - 2] + 1)
return dp[m][n]
def weighted_distance(a, b, sub, indel):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
dp[i][0] = dp[i - 1][0] + indel
for j in range(1, n + 1):
dp[0][j] = dp[0][j - 1] + indel
for i in range(1, m + 1):
for j in range(1, n + 1):
x, y = a[i - 1], b[j - 1]
cost = 0 if x == y else sub[frozenset((x, y))]
dp[i][j] = min(dp[i - 1][j] + indel, dp[i][j - 1] + indel, dp[i - 1][j - 1] + cost)
return dp[m][n]
def all_strings(alphabet, max_len):
for n in range(max_len + 1):
for chars in product(alphabet, repeat=n):
yield "".join(chars)
def find_triangle_violation(dist, alphabet="abc", max_len=3):
pool = list(all_strings(alphabet, max_len))
d = {(x, y): dist(x, y) for x in pool for y in pool}
for x in pool:
for y in pool:
for z in pool:
if d[x, z] > d[x, y] + d[y, z]:
return x, y, z, d[x, z], d[x, y], d[y, z]
return None
assert find_triangle_violation(levenshtein) is None
violation = find_triangle_violation(osa_distance)
assert violation is not None
x, y, z, dxz, dxy, dyz = violation
print(f"OSA: d({x!r},{z!r})={dxz} > d({x!r},{y!r})+d({y!r},{z!r})={dxy + dyz}")
assert osa_distance("ca", "ac") == 1
assert osa_distance("ac", "abc") == 1
assert osa_distance("ca", "abc") == 3
sub = {frozenset("ac"): 10, frozenset("ab"): 1, frozenset("bc"): 1}
d_ac = weighted_distance("a", "c", sub, indel=10)
d_ab = weighted_distance("a", "b", sub, indel=10)
d_bc = weighted_distance("b", "c", sub, indel=10)
assert d_ac == 10 and d_ab + d_bc == 2
print(f"Weighted: d('a','c')={d_ac} > d('a','b')+d('b','c')={d_ab + d_bc}")Why This Matters in Practice
Metric indexes such as BK-trees and vantage-point trees skip whole subtrees using the triangle inequality. Suppose a query q is at distance 5 from a pivot p and you want results within 1. A BK-tree then only visits children whose distance to p lies in [4, 6]. If the distance is not a metric, a true match can sit in a skipped subtree, and the index returns incomplete results without any error.
| Distance | Metric? | Safe in a BK-tree? |
|---|---|---|
| Levenshtein | Yes | Yes |
| Hamming (equal lengths) | Yes | Yes |
| Indel (LCS-based) | Yes | Yes |
| Damerau-Levenshtein (unrestricted) | Yes | Yes |
| Optimal string alignment | No, triangle fails | No, can miss matches |
| Weighted, asymmetric costs | No, symmetry fails | No |
| Weighted, zero cost for distinct symbols | Pseudometric | Only if you accept merged points |
| Normalized forms (divided by length) | Depends on formula | Verify first |
Linear scans and plain pairwise comparisons do not depend on metric properties. If you only rank candidates by distance, OSA or an asymmetric cost model is fine.
Exercise
You set insertion cost to 1, deletion cost to 1, and substitution cost to 3 for every pair of distinct characters. Is the resulting weighted distance a metric? Explain using the conditions from this chapter.
Show answer
Yes. All costs are positive, insertions and deletions cost the same, and substitutions are symmetric. Substitution costs satisfy the triangle inequality (3 <= 3 + 3). Substitution costs more than delete plus insert (3 > 2), but the DP never uses it, since the min always chooses delete-plus-insert at cost 2. The distance is then the indel distance, which is a metric.
Exercise
Use the concatenation argument to explain why the triangle inequality holds for unrestricted Damerau-Levenshtein but not for OSA, using the strings "ca", "ac", and "abc".
Show answer
Concatenating the scripts gives "ca" to "ac" (transpose) and then "ac" to "abc" (insert b), costing 2. Unrestricted Damerau-Levenshtein allows editing between characters that were already transposed, so this script is valid and d("ca","abc") <= 2. OSA forbids editing a substring more than once, so it cannot use that script, and its best alignment costs 3 > 1 + 1.
Exercise
A BK-tree built with OSA distance answers a query for "ca" with radius 2. The tree's root is "ac". Explain how this setup could miss "abc".
Show answer
The query sits at distance 1 from the root. The BK-tree only searches children whose stored distance from "ac" falls in [1 - 2, 1 + 2] = [-1, 3]. "abc" is at distance 1 from "ac", so it is visited here. With other trees and radii the pruning window can leave it out, because OSA allows d("ca","abc") = 3 to exceed d("ca","ac") + d("ac","abc") = 2. The pruning rule assumes the triangle inequality, and once that fails a pruned subtree can contain a string the bound says cannot be there. A safe choice is to switch to true Damerau-Levenshtein.