Sub topic 11
Ties and Multiple Longest Subsequences
This chapter assumes you already know the bottom-up LCS table and the traceback from earlier chapters, and that you can read Python sets and functools.lru_cache.
A pair of sequences often has more than one longest common subsequence. The DP table always gives one length, but it can describe several different strings of that length. Which string your traceback returns depends on how it breaks ties.
Where Ties Come From
During traceback, a mismatch at cell (i, j) means you move either up to (i-1, j) or left to (i, j-1), whichever has the larger value. When both neighbors hold the same value, both moves lead to an optimal answer. The code has to pick one, and different picks can produce different strings.
For "ABCBDAB" and "BDCABA", the earlier traceback used dp[i - 1][j] >= dp[i][j - 1], which prefers moving up and returns BCBA. If you change >= to >, ties go left and the same table yields BDAB. Both strings have length 4 and both are correct.
| Tie rule in traceback | Condition for moving up | Result |
|---|---|---|
| Prefer up | `dp[i-1][j] >= dp[i][j-1]` | `BCBA` |
| Prefer left | `dp[i-1][j] > dp[i][j-1]` | `BDAB` |
Enumerating Every LCS
To list all distinct longest common subsequences, follow every optimal branch instead of one. On a match, every LCS of the two prefixes ends with the matched character, so you only need the diagonal move. On a mismatch, follow each neighbor whose value equals the current cell. Collecting results in sets removes duplicates that come from different paths spelling the same string.
from functools import lru_cache
def lcs_table(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])
return dp
def all_lcs(a, b):
dp = lcs_table(a, b)
@lru_cache(maxsize=None)
def back(i, j):
if i == 0 or j == 0:
return frozenset([""])
if a[i - 1] == b[j - 1]:
return frozenset(s + a[i - 1] for s in back(i - 1, j - 1))
result = set()
if dp[i - 1][j] == dp[i][j]:
result |= back(i - 1, j)
if dp[i][j - 1] == dp[i][j]:
result |= back(i, j - 1)
return frozenset(result)
return sorted(back(len(a), len(b)))
print(all_lcs("ABCBDAB", "BDCABA")) # ['BCAB', 'BCBA', 'BDAB']Choosing a Tie Rule on Purpose
For most uses, any LCS is acceptable. In diff tools, the tie rule changes how the output looks: it decides whether a moved line is reported as a deletion followed by an insertion or the other way round, and which of two identical lines counts as "kept". Pick one rule, document it, and keep it fixed so the output stays the same from run to run.
Exercise
In the traceback for "ABCBDAB" and "BDCABA", you change the mismatch condition from dp[i - 1][j] >= dp[i][j - 1] to dp[i - 1][j] > dp[i][j - 1]. Is the new code still correct, and what does it return?
Show answer
Yes. On a tie both moves lead to an optimal answer, so the result is still a longest common subsequence. The returned string changes from BCBA to BDAB, and the length stays 4.
Exercise
Why does all_lcs follow only the diagonal on a match instead of also exploring the up and left neighbors?
Show answer
When the last characters match, every LCS of those prefixes ends with that character. If an LCS ended with some other character, you could append the matched character to it and get a longer common subsequence, which is a contradiction. So the up and left branches cannot add any new longest strings.