Sub topic 12
LCS and Insert/Delete Edit Distance
This chapter assumes you already know the LCS recurrence, the bottom-up DP table, and the two-row length computation from earlier chapters. You should also be comfortable reading a short proof and with Big-O notation.
The LCS length answers a second question you may not expect: how many single-character edits does it take to turn one sequence into another? The answer holds only when the allowed edits are inserting and deleting. Under that rule, the edit distance follows directly from the LCS length, and the relationship explains why line-based diff tools are built on LCS.
Defining Insert/Delete Edit Distance
An edit operation changes a sequence by one element. This chapter allows two kinds:
- Insert: add one element at any position.
- Delete: remove one element from any position.
The insert/delete edit distance (also called indel distance) between sequences a and b is the minimum number of these operations needed to turn a into b. Substitution, which replaces one element with another in a single step, is not allowed. If you want to change X into Y, you must delete X and insert Y, which costs 2.
For a of length m and b of length n, with L the length of their LCS:
indel distance = m + n − 2L
Why the Formula Holds
The proof has two halves. First we show that m + n − 2L operations are enough. Then we show that no script can use fewer.
Upper bound: m + n − 2L operations are enough
Pick any LCS of a and b. It has length L.
- Delete every element of
athat is not part of the chosen LCS. That takesm − Ldeletions and leaves exactly the LCS. - Insert every element of
bthat is not part of the LCS, each in its correct position. That takesn − Linsertions and producesb.
The total is (m − L) + (n − L) = m + n − 2L.
Lower bound: no script can do better
Take any valid script of inserts and deletes that turns a into b. Track each original element of a through the script. Some elements are eventually deleted. The others survive into b.
Inserts and deletes never reorder elements. So the surviving elements appear in b in the same order they had in a, which makes them a common subsequence. Say k elements survive, so k ≤ L. The script must then:
- delete at least the
m − kelements ofathat did not survive, and - insert at least the
n − kelements ofbthat did not come froma.
That gives at least m + n − 2k ≥ m + n − 2L operations. A script can contain wasted steps, such as inserting an element and deleting it later, but those only add cost. Together the two bounds give the formula.
Computing It Two Ways
There are two ways to compute the distance. You can apply the formula to the LCS length. You can also write a DP over distances directly:
- Base cases:
D[i][0] = i(delete everything) andD[0][j] = j(insert everything). - If
a[i-1] == b[j-1]:D[i][j] = D[i-1][j-1]. - Otherwise:
D[i][j] = 1 + min(D[i-1][j], D[i][j-1]), meaning delete fromaor insert fromb.
Every cell satisfies D[i][j] = i + j − 2·LCS[i][j], so the distance table and the LCS table carry the same information. The program below checks this on random inputs. It also compares the result with Levenshtein distance, the more common edit distance that allows substitutions.
import random
def lcs_length_two_rows(a, b):
if len(b) > len(a):
a, b = b, a
prev = [0] * (len(b) + 1)
for x in a:
curr = [0] * (len(b) + 1)
for j, y in enumerate(b, 1):
if x == y:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
prev = curr
return prev[-1]
def indel_distance(a, b):
return len(a) + len(b) - 2 * lcs_length_two_rows(a, b)
def indel_distance_dp(a, b):
m, n = len(a), len(b)
D = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
D[i][0] = i
for j in range(n + 1):
D[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
D[i][j] = D[i - 1][j - 1]
else:
D[i][j] = 1 + min(D[i - 1][j], D[i][j - 1])
return D[m][n]
def levenshtein(a, b, sub_cost=1):
m, n = len(a), len(b)
D = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
D[i][0] = i
for j in range(n + 1):
D[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
same = a[i - 1] == b[j - 1]
D[i][j] = min(
D[i - 1][j] + 1,
D[i][j - 1] + 1,
D[i - 1][j - 1] + (0 if same else sub_cost),
)
return D[m][n]
random.seed(0)
for _ in range(2000):
a = "".join(random.choice("ABC") for _ in range(random.randint(0, 8)))
b = "".join(random.choice("ABC") for _ in range(random.randint(0, 8)))
d = indel_distance(a, b)
assert d == indel_distance_dp(a, b)
assert d == levenshtein(a, b, sub_cost=2)
assert levenshtein(a, b) <= d
print("all checks passed")
print(indel_distance("ABCBDAB", "BDCABA")) # 5
print(indel_distance("kitten", "sitting")) # 5
print(levenshtein("kitten", "sitting")) # 3
print(levenshtein("kitten", "sitting", 2)) # 5The third assertion shows a useful identity. Indel distance equals Levenshtein distance with substitution cost 2. A substitution that costs 2 is never cheaper than a delete plus an insert, so the DP never benefits from using one.
Indel Distance vs. Levenshtein Distance
| Property | Insert/delete distance | Levenshtein distance |
|---|---|---|
| Allowed operations | insert, delete | insert, delete, substitute |
| Closed form | `m + n − 2·LCS` | none in terms of LCS |
| `kitten` → `sitting` | 5 (LCS `ittn`, length 4) | 3 |
| `abc` → `xyz` | 6 | 3 |
| Range | `abs(m − n)` to `m + n` | `abs(m − n)` to `max(m, n)` |
| Parity | always the same parity as `m + n` | any parity |
| Typical use | line diffs, patch generation | spelling correction, fuzzy matching |
Which one to use depends on what an edit means in your domain. In a text diff, a changed line counts as one line removed plus one line added, and the output shows it that way. Indel distance matches that model, and the alignment behind it tells you which lines are kept unchanged. Levenshtein distance fits typos better, because one mistyped character feels like one error, not two.
Edge Cases and Useful Bounds
These facts follow directly from d = m + n − 2L with 0 ≤ L ≤ min(m, n):
- Empty input. If
ais empty,L = 0andd = n, so you insert everything. - Identical sequences.
L = m = n, sod = 0. - No shared elements.
L = 0, sod = m + n. Everything is deleted and everything is reinserted. - One sequence is a subsequence of the other.
L = min(m, n), sod = abs(m − n). This is the minimum possible distance. - Parity.
dandm + nare always both even or both odd. Use this as a quick sanity check on hand calculations and test outputs. - Metric. Indel distance is symmetric, it is zero only for equal sequences, and it obeys the triangle inequality. Each operation can be reversed by the opposite operation at the same cost, and editing
a → b → cgives a valida → cscript.
Common Mistakes
- Dropping the factor of 2. Writing
m + n − Lcounts each kept element only once. Each LCS element saves both a deletion and an insertion. - Wrong base cases in the direct DP. If you set
D[i][0] = 0instead ofi, you are treating leftover characters as free to delete. - Using Levenshtein for diff-style output. A substitution has no clean representation in a line-based diff, and the Levenshtein alignment may line up content differently from what users expect to see.
- Expecting the distance to pick a script. Many edit scripts can reach the minimum, one for each choice of LCS. The traceback tie-breaking rule from the earlier chapter decides which one you get.
To recover the actual edit script, you trace back through the same table you used to find the LCS. Matched cells become "keep", upward moves become "delete", and leftward moves become "insert". The next chapter turns that traceback into diff output.
Exercise
Sequence a has length 5 and sequence b has length 8. Can their insert/delete edit distance be 4? What are the smallest and largest possible values?
Show answer
No. The distance is 13 − 2L, which is always odd, so 4 is impossible. L can be at most 5, which gives a minimum of 3 (a is a subsequence of b). L can be as small as 0, which gives a maximum of 13 (no shared elements).
Exercise
Compute the insert/delete distance and the Levenshtein distance between "abcd" and "acbd". Explain why they differ.
Show answer
One LCS is "abd" (or "acd"), with length 3. The indel distance is 4 + 4 − 6 = 2: delete one middle letter and reinsert it on the other side. The Levenshtein distance is also 2, achieved by substituting both middle letters. Here the two are equal. They differ only when substitutions replace delete-plus-insert pairs that cost 2 each: for "abc" vs "xyz", the indel distance is 6 and the Levenshtein distance is 3.
Exercise
Why does setting the substitution cost to 2 in the Levenshtein DP always reproduce the insert/delete distance?
Show answer
A substitution with cost 2 is never cheaper than a deletion plus an insertion, which also cost 2 together. Any optimal script that uses a substitution can therefore swap it for a delete and an insert without raising the cost. So the minimum equals the minimum over insert/delete-only scripts, which is m + n − 2L.