Sub topic 16
Edit Distance in Practice
This chapter assumes you have read the earlier chapters. You should be able to fill the DP table, run the two-row version, add a distance threshold, and tell Levenshtein, Hamming, OSA, and indel distance apart. Here we take those tools into four real settings: spell checking, fuzzy search, diff, and bioinformatics. For each one, we look at which variant fits and which mistakes are common.
Same Core, Different Questions
Every application below uses the same prefix recurrence. They change three things:
- What counts as a symbol. It can be a character, a line of a file, a DNA base, or a word token.
- What the costs are. Costs can be unit, weighted, or indel-only, and transpositions can be allowed or not.
- What is being compared. You might compare a whole string to a whole string, a pattern to any substring of a text, or a query to many dictionary entries.
Spell Checking
A spell checker gets a word that is not in its dictionary and must suggest the words closest to it. Most real typos are within edit distance 1 or 2 of the intended word, so a threshold is natural. Many typos are adjacent swaps ("teh" for "the"), so OSA distance usually beats plain Levenshtein here.
The simplest correct approach scans the dictionary and uses a bounded distance. It skips a word early when the length gap already exceeds k, and it stops filling the table when every cell in a row exceeds k.
def bounded_distance(a, b, k):
"""Return Levenshtein distance if it is <= k, else None."""
if abs(len(a) - len(b)) > k:
return None
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)))
if min(curr) > k:
return None # every path already costs more than k
prev = curr
return prev[-1] if prev[-1] <= k else None
def suggest(word, dictionary, k=2):
scored = []
for w in dictionary:
d = bounded_distance(word, w, k)
if d is not None:
scored.append((d, w))
return sorted(scored)
words = ["spelling", "spline", "peeling", "selling", "sapling", "dwelling"]
result = suggest("speling", words)
print(result)
assert result[0] == (1, "spelling")
assert all(d == 2 for d, w in result[1:])The output shows the main practical issue. Four candidates tie at distance 2, and alphabetical order is a poor tie-breaker. Production spell checkers combine distance with other signals:
- Word frequency. "selling" is more likely than "sapling" for most users.
- Keyboard-aware substitution costs. Typing
rfore(adjacent keys) should cost less than typingzfore. This is the weighted-costs chapter applied directly. - Phonetic similarity, which handles errors like "fone" for "phone".
A linear scan of a 500,000-word dictionary costs one bounded DP per word. That is fine for one query and too slow for a server handling thousands. Indexes avoid most of the comparisons:
- A BK-tree uses the triangle inequality. If the query is at distance
dfrom a node, only subtrees at distanced-ktod+kfrom that node can hold matches. This is valid only because Levenshtein and true Damerau-Levenshtein are metrics. OSA breaks the triangle inequality, so a BK-tree built on OSA can silently miss results. - Deletion neighborhoods (the SymSpell approach) precompute every string reachable by up to
kdeletions from each dictionary word. Lookup then becomes hash probes. - Levenshtein automata compile the query into a finite automaton that accepts exactly the strings within distance
k. The automaton can then walk a trie or an FST index. Lucene's fuzzy queries work this way.
Fuzzy Search Inside Text
Sometimes the question changes from "how far is word A from word B?" to "where does pattern P approximately occur inside a long text T?" In that case, charging for the text before and after the match is wrong. Sellers' algorithm fixes this with one change: the first row is all zeros, so a match may start at any position of the text. You then read the answer from the last row of the pattern at every text position.
def best_substring_match(pattern, text):
"""Minimum edit distance between pattern and any substring of text,
and the text index where that best match ends."""
m = len(pattern)
prev = list(range(m + 1)) # column for empty text prefix
best = (prev[m], 0)
for j, ct in enumerate(text, 1):
curr = [0] # empty pattern matches anywhere for free
for i, cp in enumerate(pattern, 1):
curr.append(min(prev[i] + 1, curr[i - 1] + 1, prev[i - 1] + (cp != ct)))
if curr[m] < best[0]:
best = (curr[m], j)
prev = curr
return best
dist, end = best_substring_match("survey", "the surgery was fine")
print(dist, end, repr("the surgery was fine"[:end]))
assert dist == 2This is the same O(mn) recurrence with columns indexed by text position. Tools like agrep and the TRE regex library use this formulation. They speed it up with the bit-parallel technique from Myers' algorithm, which handles patterns up to the machine word size in O(n) word operations.
Diff and Version Control
The diff and git diff tools compare files line by line. Each line is one symbol, compared by hash. Substitution is not offered as a primitive. A changed line is shown as one deletion plus one insertion, so this is indel distance, which is equivalent to the longest common subsequence:
indel_distance(a, b) = len(a) + len(b) - 2 * LCS(a, b)Files can have tens of thousands of lines, so the full O(mn) table is too expensive. Myers' O(ND) diff algorithm (a different paper from the bit-parallel one) runs in time proportional to file size times the number of differences. That makes it fast when two versions are similar, which is the common case. Git also offers patience and histogram diff. These anchor on unique lines first, which often gives edit scripts that read better to humans, even when they are not minimal.
Bioinformatics
DNA and protein comparison uses the weighted form of the recurrence, usually written as similarity to maximize instead of cost to minimize:
- Needleman-Wunsch does global alignment. It has the same structure as Levenshtein, with scores from a substitution matrix such as BLOSUM62 for proteins.
- Smith-Waterman does local alignment. It clamps every cell at zero, so an alignment can start and end anywhere. This plays the same role as Sellers' zero first row.
- Affine gap penalties charge more to open a gap than to extend one, because one long insertion is biologically more likely than many scattered ones. Affine gaps need three DP tables instead of one.
- Banded alignment restricts the DP to a diagonal band, as in the threshold chapter. Read aligners for sequencing data use it because reads are expected to differ from the reference by only a few edits.
At genome scale, even banded DP is too slow to run against every position. Tools such as BLAST and minimap2 first find short exact "seed" matches using hash tables or indexes. They run DP only around those seeds. Quadratic hardness under SETH is the theoretical reason this heuristic, filter-then-verify design is unavoidable in practice.
Choosing a Variant
| Task | Symbol | Variant | Speedup in practice |
|---|---|---|---|
| Spell suggestion | character | OSA or Damerau-Levenshtein, keyboard weights | threshold k ≤ 2, BK-tree (true metric only), Levenshtein automaton |
| Fuzzy search in text | character | Levenshtein, substring (Sellers) | bit-parallel Myers |
| Record deduplication | token or character | Levenshtein normalized by length | blocking keys before comparison |
| File diff | line | indel / LCS | Myers O(ND), patience or histogram |
| Fixed-length codes | bit or character | Hamming | XOR and popcount |
| DNA/protein alignment | base or amino acid | weighted, affine gaps, global or local | seeding plus banded DP |
Common errors in practice:
- Comparing raw distances across lengths. A distance of 3 is large for 4-letter words and small for 40-letter titles. Normalize, for example as
d / max(len(a), len(b)), before applying a single cutoff. - Ignoring Unicode. In Python,
"é"may be one code point or two (eplus a combining accent). Normalize withunicodedata.normalize("NFC", s)first, and remember that case folding is a separate step. - Using OSA where a metric is assumed, as in the BK-tree warning above.
- Running full DP when a threshold exists. If you only care whether d ≤ k, banding cuts the cost from O(mn) to O(k·min(m, n)).
Exercise
You build a BK-tree over a product catalog using OSA distance to tolerate swapped letters. Some queries miss products that are clearly within distance 2. Explain why, and give two fixes.
Show answer
BK-tree pruning relies on the triangle inequality, and OSA violates it. For example, OSA("ca","abc") = 3 while OSA("ca","ac") + OSA("ac","abc") = 1 + 1 = 2. So the tree can prune a subtree that actually contains a match. Fix 1: use true (unrestricted) Damerau-Levenshtein, which is a metric. Fix 2: build the tree on Levenshtein, query with a radius of k, and re-rank the candidates with OSA afterward. A swap costs at most 2 under Levenshtein, so you may need to widen the radius to avoid missing swap-only matches.
Exercise
In bestsubstringmatch, what single change turns it back into ordinary whole-string Levenshtein distance between pattern and text, and where would you read the answer?
Show answer
Set curr[0] = j instead of 0, so skipping leading text characters costs one per character. Then read the answer only from the final column (prev[m] after the last text character) instead of taking the minimum over all text positions.
Exercise
Two log lines are compared character by character. "ERROR disk full on /dev/sda1" and "ERROR disk full on /dev/sdb1" have distance 1, and "WARN cpu" and "INFO cpu" have distance 4. A teammate concludes the second pair is more different. What is wrong with that reasoning, and what would you do instead?
Show answer
Raw distance ignores length and meaning. The first pair differs by 1 out of about 28 characters, and the second by 4 out of 8, but the severity token change is the semantically important one. Normalize by length for a fair numeric comparison. Better, tokenize into words and compute distance over tokens, possibly with weights per field, so a changed severity level counts as one significant substitution.