Sub topic 16
Beyond Two Sequences: Multi-Sequence LCS and NP-Hardness
This chapter assumes you already know the two-sequence LCS recurrence, top-down memoization with lru_cache, the bottom-up table with traceback, and Big-O notation. Here you will extend the recurrence to any number of sequences. You will see why the cost explodes as more sequences are added, and why one common shortcut gives wrong answers. The chapter ends with what NP-hardness means for this problem in practice.
Generalizing the Recurrence to k Sequences
Suppose you have k sequences s1, s2, ..., sk. A common subsequence must be a subsequence of every one of them. For two sequences, the subproblem was a pair of positions (i, j). For k sequences, the subproblem is a tuple of k positions (i1, i2, ..., ik), one per sequence, and you are looking for the LCS of all the suffixes that start at those positions.
The same optimal-substructure argument carries over:
- Base case: if any position has reached the end of its sequence, the answer is 0. An empty sequence has no common subsequence except the empty one.
- All current characters match: if s1[i1] = s2[i2] = ... = sk[ik], take that character and advance every index: 1 + LCS(i1+1, ..., ik+1).
- Otherwise: at least one sequence's current character cannot be the first character of the LCS. Try advancing each index on its own and keep the best result: the maximum over t of LCS with index t advanced by one.
The third case has k branches instead of 2. To see why this is correct, take an optimal common subsequence and look at where its first character sits in each sequence. If it sat at the current position in every sequence, all current characters would match, which contradicts the case we are in. So in some sequence t, the character sits later than it. Skipping st[i_t] then loses nothing.
A Working Implementation
The memoized version below turns the recurrence directly into code. The cache key is the tuple of positions.
from functools import lru_cache
def lcs_multi(seqs):
seqs = tuple(seqs)
k = len(seqs)
@lru_cache(maxsize=None)
def solve(idx):
if any(i == len(s) for i, s in zip(idx, seqs)):
return 0
first = seqs[0][idx[0]]
if all(s[i] == first for i, s in zip(idx, seqs)):
return 1 + solve(tuple(i + 1 for i in idx))
best = 0
for t in range(k):
nxt = list(idx)
nxt[t] += 1
best = max(best, solve(tuple(nxt)))
return best
return solve(tuple([0] * k))
print(lcs_multi(["ABCBDAB", "BDCABA", "BCBA"])) # 4
print(lcs_multi(["AB", "BA", "B"])) # 1The first call returns 4 because "BCBA" is a subsequence of all three strings. Each recursive call advances at least one index, so the recursion depth is at most the sum of the lengths. That is fine for short inputs, but for long ones you would switch to a bottom-up loop over the k-dimensional table, in an order where every cell's successors are filled before the cell itself.
The Cost Grows Exponentially in k
The table has one cell per tuple of positions, so it holds (n1+1)(n2+1)...(nk+1) cells. Each cell does O(k) work to compare characters and up to k lookups. If all sequences have length n:
- Time: O(k · (n+1)^k)
- Space: O((n+1)^k) for the full table
The two-row trick from earlier chapters still applies in a generalized form. You keep only the "slab" of cells where the first index is fixed, which removes one factor of n from the space cost. The time cost stays the same.
| Sequences (k) | Length (n) | Table cells, about (n+1)^k |
|---|---|---|
| 2 | 1,000 | 1.0 × 10^6 |
| 3 | 1,000 | 1.0 × 10^9 |
| 4 | 1,000 | 1.0 × 10^12 |
| 10 | 100 | 1.1 × 10^20 |
For any fixed k the algorithm is polynomial in n. Three short sequences are easy, and three sequences of length 1,000 are already a billion-cell job. Each extra sequence multiplies the work by roughly n.
The Pairwise-Fold Trap
The obvious shortcut is to compute LCS(s1, s2), then the LCS of that result with s3, and so on. This shortcut is wrong. The pairwise step commits to one specific LCS, and the tie-breaking rule in the traceback decides which one. The chosen string may share less with the next sequence than another, equally long option would have.
def lcs(a, b):
m, n = len(a), len(b)
dp = [[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]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
out = []
i, j = m, n
while i > 0 and j > 0:
if a[i - 1] == b[j - 1]:
out.append(a[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return "".join(reversed(out))
def lcs_fold(seqs):
acc = seqs[0]
for s in seqs[1:]:
acc = lcs(acc, s)
return acc
seqs = ["AB", "BA", "B"]
folded = lcs_fold(seqs)
print(repr(folded), len(folded)) # '' 0LCS("AB", "BA") has two answers, "A" and "B". This traceback picks "A", and "A" shares nothing with "B", so the fold returns the empty string. The true three-way LCS is "B", with length 1, as lcs_multi showed above.
The reverse bound is also cheap. The true k-way LCS can be no longer than the smallest pairwise LCS among any two of the sequences. When the fold's lower bound equals this upper bound, you have proved the fold's answer is optimal without running the k-dimensional DP.
What NP-Hardness Means Here
When the number of sequences is part of the input rather than a fixed constant, the problem changes character. Maier (1978) proved that the decision version is NP-complete. The decision version asks: "Given k sequences and an integer L, is there a common subsequence of length at least L?" The optimization version is therefore NP-hard. No known algorithm runs in time polynomial in both n and k, and finding one would show P = NP.
Two clarifications prevent common confusion:
- NP-hard does not mean the problem is slow for every input. For fixed k, the DP above is polynomial. The hardness lies in the n^k growth, where the exponent depends on the input.
- The hardness holds even when parameterized by k. Bodlaender, Downey, Fellows and Wareham (1995) showed the problem is W[1]-hard with k as the parameter. Informally, you should not expect an algorithm of the form f(k) · n^c with a constant c that does not depend on k.
Practical Decision Criteria
| Situation | Reasonable approach |
|---|---|
| k = 2 | Standard O(mn) DP, with Hirschberg if you need the string in linear space |
| k = 3 or 4, short sequences | Exact k-dimensional DP |
| Larger k or long sequences, exact answer required | Branch-and-bound or A* search over the state space, pruned with the pairwise upper bound |
| Approximate answer acceptable | Pairwise fold or other heuristics, checked against the upper bound |
| Merging files (diff3, git merge) | Avoid k-way LCS: diff each version against the common base pairwise |
Tools that look like k-way comparison usually avoid it. A three-way merge computes two ordinary diffs, base-to-ours and base-to-theirs, then combines the hunks. In bioinformatics, multiple sequence alignment generalizes LCS with scoring and gaps. Widely used tools such as Clustal rely on progressive heuristics for the same reason: exact k-dimensional alignment is not feasible at scale.
Exercise
In the k-sequence recurrence, how many subproblems does a mismatch cell consult, and how many cells does the full table have for k = 5 sequences of length 20 each?
Show answer
A mismatch cell consults k = 5 subproblems, one for each index advanced on its own. The table has (20+1)^5 = 4,084,101 cells.
Exercise
Explain why the pairwise fold LCS(LCS(s1, s2), s3) always gives a lower bound on the true three-way LCS, and give an upper bound you can compute with only two-sequence DP.
Show answer
The folded result is a subsequence of LCS(s1, s2), which is a subsequence of both s1 and s2, and it is also a subsequence of s3. So it is a common subsequence of all three, and its length cannot exceed the optimum. For an upper bound, any common subsequence of all three is a common subsequence of each pair, so the true LCS length is at most min(LCS(s1,s2), LCS(s1,s3), LCS(s2,s3)).
Exercise
A colleague says "multi-sequence LCS is NP-hard, so even three sequences of length 50 are intractable." What is wrong with this claim?
Show answer
NP-hardness applies when k is part of the input. For fixed k = 3, the DP runs in O(3 · 51^3), which is about 400,000 cell operations and finishes instantly. The cost becomes impractical only as k grows, because the exponent of n is k.