Sub topic 2
Defining Levenshtein Distance
This chapter assumes you can read Python, work with strings and lists, and read Big-O notation. The previous chapter introduced the three edit operations. Here we turn them into a precise number, the Levenshtein distance, and look at what that number guarantees before we compute it efficiently in later chapters.
The Definition
Let a and b be strings over some alphabet. An edit script from a to b is a sequence of operations that turns a into b, where each operation is one of these:
- Insertion: add one character at any position.
- Deletion: remove one character.
- Substitution: replace one character with a different character.
The Levenshtein distance lev(a, b) is the length of the shortest edit script from a to b. Every operation costs 1. Characters that stay in place cost nothing.
The definition says nothing about how to find the shortest script. It only says which number we want. Later chapters build the algorithm. This one pins down the target.
A Worked Example
The standard example is kitten to sitting:
kittentositten: substitutekwiths.sittentosittin: substituteewithi.sittintositting: insertgat the end.
That script has three operations, so lev("kitten", "sitting") ≤ 3. To claim the distance is exactly 3, we also have to rule out every shorter script. The lengths differ by 1, so at least one insertion is needed. The strings also disagree at the first character and at the fifth, and a single insertion cannot fix both mismatches. So no script of length 2 exists, and the distance is 3.
Two Views: Scripts and Alignments
An edit script is a sequence of actions. The same information can be written as an alignment: put the two strings in rows, insert gaps (-) so the rows have equal length, and read each column.
| Column | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| a | k | i | t | t | e | n | - |
| b | s | i | t | t | i | n | g |
| Operation | sub | keep | keep | keep | sub | keep | ins |
Each column holds one of four things:
- The same character in both rows: a keep, cost 0.
- Different characters: a substitution, cost 1.
- A character over a gap: a deletion, cost 1.
- A gap over a character: an insertion, cost 1.
A column with two gaps is never allowed. The cost of an alignment is the number of non-keep columns. The Levenshtein distance is the minimum cost over all alignments.
The alignment view clears up a point that often confuses people. In an alignment, the order you apply the operations in doesn't matter. Each operation touches a different column, so any shortest script can be rearranged to work left to right without changing its length. That is why the next chapter can build the distance from prefixes.
Properties That Follow Directly from the Definition
Several facts follow from the definition alone, before any algorithm. They work well as sanity checks on an implementation.
| Property | Statement | Reason |
|---|---|---|
| Identity | `lev(a, b) = 0` exactly when `a == b` | An empty script changes nothing, and any non-empty shortest script changes something |
| Symmetry | `lev(a, b) = lev(b, a)` | Reverse the script: insertions become deletions, deletions become insertions, and substitutions swap direction |
| Lower bound | `lev(a, b) ≥ abs(len(a) - len(b))` | Only insertions and deletions change length, and each changes it by exactly 1 |
| Upper bound | `lev(a, b) ≤ max(len(a), len(b))` | Substitute across the shorter length, then insert or delete the rest |
| Empty string | `lev(a, "") = len(a)` | You must delete every character, and nothing else helps |
Symmetry holds because all three operations cost the same. Once insertions and deletions have different prices, which a later chapter on weighted costs covers, the distance can depend on direction. The triangle inequality also holds, and the chapter on metric properties proves it.
Example Pairs
| a | b | Distance | One shortest script |
|---|---|---|---|
| `""` | `""` | 0 | (none) |
| `abc` | `""` | 3 | delete a, b, c |
| `flaw` | `lawn` | 2 | delete f, insert n |
| `book` | `back` | 2 | sub o→a, sub o→c |
| `sunday` | `saturday` | 3 | insert a, insert t, sub n→r |
| `intention` | `execution` | 5 | delete i, sub n→e, sub t→x, insert c, sub n→u |
Computing It Straight from the Definition
The definition already gives an algorithm, though a slow one. Treat every string as a node in a graph, and connect two strings when a single operation turns one into the other. The Levenshtein distance is then the shortest path length from a to b, and breadth-first search finds it.
One observation keeps the search finite. A shortest script never needs to insert or substitute a character that doesn't appear in b, because that character would have to be removed or changed again later. So the only characters we need are the ones in b.
from collections import deque
def neighbors(s, alphabet):
"""All strings reachable from s with exactly one edit."""
for i in range(len(s)):
yield s[:i] + s[i + 1:] # delete s[i]
for c in alphabet:
if c != s[i]:
yield s[:i] + c + s[i + 1:] # substitute s[i] with c
for i in range(len(s) + 1):
for c in alphabet:
yield s[:i] + c + s[i:] # insert c before position i
def levenshtein_bfs(a, b):
"""Shortest edit script length, found by breadth-first search."""
alphabet = sorted(set(b))
seen = {a}
queue = deque([(a, 0)])
while queue:
s, d = queue.popleft()
if s == b:
return d
for t in neighbors(s, alphabet):
if t not in seen:
seen.add(t)
queue.append((t, d + 1))
assert levenshtein_bfs("kitten", "sitting") == 3
assert levenshtein_bfs("flaw", "lawn") == 2
assert levenshtein_bfs("abc", "") == 3
assert levenshtein_bfs("", "") == 0
assert levenshtein_bfs("abc", "bca") == 2
print("all checks passed")This code is correct, and it makes a good test oracle for small inputs. Its cost is exponential, though. Each string has roughly (2·|Σ| + 1)·n neighbors, where Σ is the alphabet, and the search goes as deep as the distance. Even kitten to sitting visits hundreds of thousands of strings. The dynamic programming chapters replace this search with an O(mn) table.
Common Errors
Comparing Position by Position
A tempting shortcut is to line the strings up at index 0 and count mismatches. For abc and bca, every position differs, so the shortcut gives 3. The true distance is 2: delete the leading a and append a at the end. Comparing position by position only works when you restrict yourself to substitutions, which is Hamming distance, the subject of the next chapter. Levenshtein distance allows the strings to shift relative to each other.
Greedy Choices
A greedy algorithm that fixes the first mismatch with whatever operation looks cheapest right now can commit to a bad alignment. The definition asks for a global minimum. Finding it requires considering every way the prefixes could line up, and that is exactly what the recurrence in the next chapter does.
Counting Matches as Operations
Keeping a character is free. An implementation that charges 1 for every column, or that counts "substitute x with x", inflates every result.
Forgetting What a "Character" Is
Python indexes strings by Unicode code point, so the distance depends on how the text is encoded. The letter é can be stored as one code point or as e followed by a combining accent.
import unicodedata
composed = "caf\u00e9" # é as one code point
decomposed = "cafe\u0301" # e + combining acute accent
print(composed == decomposed) # False
print(len(composed), len(decomposed)) # 4 5
nfc = lambda s: unicodedata.normalize("NFC", s)
print(nfc(composed) == nfc(decomposed)) # TrueWithout normalization, those two visually identical strings are at distance 1 or more. Decide on a unit (bytes, code points, normalized code points, or words) before comparing, and apply it consistently. Case folding works the same way: lev("Cat", "cat") is 1 unless you lowercase both strings first.
Exercise
What is lev("horse", "ros")? Give one shortest edit script and explain why no shorter script exists.
Show answer
The distance is 3. One shortest script: substitute h with r (rorse), delete the first r (orse), delete e (ors)... a cleaner version is: substitute h→r giving "rorse", delete r at index 2 giving "rose", delete e giving "ros". The length difference is 2, so at least two deletions are needed. After any two deletions, "horse" becomes a 3-letter subsequence of it, such as "hos", "ors", or "rse", and none of those equals "ros". So a third operation is required.
Exercise
String a has length 4 and string b has length 9. What range of values can lev(a, b) take? Give example strings for the smallest and largest values.
Show answer
The distance lies between 5 and 9 inclusive. The lower bound 5 = 9 − 4 is reached when a is a subsequence of b, for example a = "abcd" and b = "abcdxxxxx". The upper bound 9 = max(4, 9) is reached when the strings share no characters, for example a = "aaaa" and b = "bbbbbbbbb".
Exercise
Explain why lev(a, b) = lev(b, a), and name a change to the definition that would break this property.
Show answer
Every edit script from a to b can be reversed into a script from b to a of the same length. Each insertion becomes a deletion, each deletion becomes an insertion, and each substitution x→y becomes y→x. All three operations cost 1, so the reversed script costs the same, and the minimums are equal. Giving insertions and deletions different costs (for example, insertion 1 and deletion 2) breaks symmetry, because reversing the script swaps which operations you pay for.