Sub topic 10
Indel Distance and the Longest Common Subsequence
This chapter assumes you have read the earlier chapters on the Levenshtein recurrence, filling the DP table, traceback, and custom operation costs. You should be comfortable reading a recurrence over prefixes dp[i][j] and running Python code that builds a 2D list.
Levenshtein distance allows three operations. Many tools allow only two: insert a character, and delete a character. Substitution is not available. The minimum number of insertions and deletions needed to turn a into b is called the indel distance (from "insertion/deletion"). It is also called LCS distance, because it is determined exactly by the longest common subsequence of the two strings.
Why drop substitution?
There are several reasons to restrict the operation set.
- Line-based diff. When
difforgit diffcompares files, a "changed line" is reported as one line removed and one line added. The underlying model has no substitution. Myers' diff algorithm computes a shortest edit script of inserts and deletes. - Alignment semantics. In some sequence-comparison settings, a mismatch is not a meaningful event. Only kept elements and gaps matter.
- Similarity scores. The normalized form of indel distance, covered below, has a simple interpretation as "the fraction of characters the two strings share in order."
Subsequence versus substring
A subsequence of a string is what remains after deleting zero or more characters, keeping the rest in their original order. The characters do not have to be adjacent. "ittn" is a subsequence of "kitten" (kitten) and of "sitting" (sitting).
A substring is a contiguous run of characters. "itt" is a common substring of both words, but "ittn" is not a substring of either.
The identity: indel = m + n − 2·LCS
Take any script of insertions and deletions that turns a (length m) into b (length n). Some characters of a are never deleted. They survive into b in the same relative order, so they form a common subsequence of a and b. Call its length k.
Every other character of a must be deleted, which costs m − k deletions. Every character of b that did not come from a survivor must be inserted, which costs n − k insertions. The script therefore costs
(m − k) + (n − k) = m + n − 2k.
Going the other way, any common subsequence of length k gives a script of exactly that cost: delete everything outside it from a, then insert everything outside it into b. The cost decreases as k grows, so the minimum is reached when k is as large as possible:
indel(a, b) = m + n − 2 · LCS(a, b)
For "kitten" and "sitting", LCS = 4 ("ittn"), so indel = 6 + 7 − 8 = 5. One optimal script deletes k, inserts s, deletes e, inserts i, and appends g. Levenshtein distance is 3 for this pair, because it can substitute k→s and e→i at a cost of 1 each.
Two equivalent recurrences
You can compute indel distance directly, or compute the LCS and apply the identity.
The direct indel recurrence is the Levenshtein recurrence with the substitution case removed:
dp[i][0] = i,dp[0][j] = j- if
a[i-1] == b[j-1]:dp[i][j] = dp[i-1][j-1] - otherwise:
dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1])
The LCS recurrence maximizes the number of kept characters instead of minimizing cost:
L[i][0] = L[0][j] = 0- if
a[i-1] == b[j-1]:L[i][j] = L[i-1][j-1] + 1 - otherwise:
L[i][j] = max(L[i-1][j], L[i][j-1])
The two tables are related cell by cell: dp[i][j] = i + j − 2·L[i][j]. If you substitute this into the LCS recurrence, you get the indel recurrence back.
In the match case, both recurrences take the diagonal without comparing it against the other neighbors. This is safe. When the last characters match, keeping both can never give a worse result than deleting or inserting one of them. An exchange argument shows that any optimal solution can be rearranged to keep that pair.
Indel as weighted Levenshtein
The chapter on custom costs introduced a recurrence with a separate cost for each operation. Set insertion and deletion cost to 1 and substitution cost to 2. A substitution then costs the same as a deletion followed by an insertion, so it never beats that pair. The weighted distance equals indel distance. Any substitution cost of 2 or more gives the same answer. A cost of 3 or more means substitution is never used at all.
This gives you two independent implementations that you can test against each other.
import random
def lcs_table(a, b):
m, n = len(a), len(b)
L = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
L[i][j] = L[i - 1][j - 1] + 1
else:
L[i][j] = max(L[i - 1][j], L[i][j - 1])
return L
def lcs_string(a, b):
L = lcs_table(a, b)
i, j = len(a), len(b)
out = []
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i, j = i - 1, j - 1
elif L[i - 1][j] >= L[i][j - 1]:
i -= 1
else:
j -= 1
return "".join(reversed(out))
def indel_distance(a, b):
L = lcs_table(a, b)
return len(a) + len(b) - 2 * L[len(a)][len(b)]
def indel_direct(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):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1])
return dp[m][n]
def weighted_levenshtein(a, b, ins=1, dele=1, sub=1):
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] = i * dele
for j in range(1, n + 1):
dp[0][j] = j * ins
for i in range(1, m + 1):
for j in range(1, n + 1):
cost = 0 if a[i - 1] == b[j - 1] else sub
dp[i][j] = min(dp[i - 1][j] + dele,
dp[i][j - 1] + ins,
dp[i - 1][j - 1] + cost)
return dp[m][n]
assert lcs_string("kitten", "sitting") == "ittn"
assert indel_distance("kitten", "sitting") == 5
assert indel_distance("flaw", "lawn") == 2
random.seed(0)
for _ in range(2000):
a = "".join(random.choices("abc", k=random.randint(0, 8)))
b = "".join(random.choices("abc", k=random.randint(0, 8)))
d = indel_distance(a, b)
assert d == indel_direct(a, b) == weighted_levenshtein(a, b, sub=2)
assert weighted_levenshtein(a, b, sub=1) <= d <= 2 * weighted_levenshtein(a, b, sub=1)
print("all checks passed")The traceback in lcs_string uses the same idea as the edit-script traceback from earlier: at each cell, move to a neighbor that produced the current value. The two-row trick also applies to both tables if you need only the number and not the subsequence.
How indel compares to Levenshtein
| Pair | LCS | Levenshtein | Indel |
|---|---|---|---|
| `flaw`, `lawn` | 3 | 2 | 2 |
| `kitten`, `sitting` | 4 | 3 | 5 |
| `ab`, `ba` | 1 | 2 | 2 |
| `abc`, `xyz` | 0 | 3 | 6 |
Three properties are visible in the table and are checked by the random test above:
- Lev ≤ indel ≤ 2·Lev. Every indel script is also a valid Levenshtein script, which gives the lower bound. Replacing each substitution in an optimal Levenshtein script with a delete and an insert gives the upper bound.
- indel ≥ |m − n|. Each operation changes the length by exactly one.
- Parity. indel has the same parity as m + n, because it equals m + n − 2k. Indel distance between strings of lengths 6 and 7 is always odd.
Normalized similarity
Because indel ≤ m + n, the value 1 − indel / (m + n) lies in [0, 1]. By the identity, it simplifies to 2·LCS / (m + n). RapidFuzz's fuzz.ratio is documented as this normalized indel similarity, scaled to 0–100. For kitten/sitting, the similarity is 8/13 ≈ 0.615.
Cost and hardness
Both recurrences fill an (m+1) × (n+1) table, so they take O(mn) time. The LCS problem has the same conditional quadratic lower bound under SETH as Levenshtein distance, which a later chapter discusses. In practice, diff tools run fast because they use output-sensitive algorithms. Myers' O((m+n)·D) algorithm, where D is the indel distance, runs quickly when files differ only a little.
Exercise
Compute the LCS and the indel distance of "AGGTAB" and "GXTXAYB" by hand, then give the Levenshtein distance as well and confirm the bounds Lev ≤ indel ≤ 2·Lev hold.
Show answer
The LCS is "GTAB" with length 4, so indel = 6 + 7 − 2·4 = 5. The Levenshtein distance is 4. For example, substitute A→G and G→X, insert X, substitute T→Y... A cleaner check is the code: weighted_levenshtein("AGGTAB", "GXTXAYB") returns 4. The bounds hold because 4 ≤ 5 ≤ 8.
Exercise
Without computing a table, explain why indel("abcd", "xyz") cannot equal 4.
Show answer
Indel distance always has the same parity as m + n because it equals m + n − 2·LCS. Here m + n = 7, which is odd, so the distance must be odd. In fact LCS = 0, so the distance is 7.
Exercise
A teammate sets substitution cost to 1.5 in weighted_levenshtein and expects indel distance. What do they get, and why is it wrong?
Show answer
A substitution costing 1.5 is cheaper than a delete plus an insert, which cost 2, so mismatched aligned pairs are substituted. The result is less than or equal to indel distance and differs whenever a substitution appears in the optimal script. For kitten/sitting the result is 1.5 + 1.5 + 1 = 4.0, not 5. Substitution cost must be at least 2.