Sub topic 11
Ties and Multiple Longest Subsequences
This chapter assumes you have already built the bottom-up LCS table and written the traceback from the earlier chapters. You should be comfortable reading dp[i][j] as "the LCS length of a[:i] and b[:j]." We use the same running example, a = "ABCBDAB" and b = "BDCABA", whose LCS length is 4.
Up to now we have said that the traceback recovers one longest common subsequence. That wording matters. Most pairs of inputs have several different subsequences of maximum length, and the traceback picks one of them based on a rule you may not have noticed you chose.
Where Ties Come From
During traceback, at a cell where a[i-1] != b[j-1], the recurrence says:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
If the two neighbors hold different values, only one move keeps you on an optimal path. If they are equal, both moves are optimal. Moving up drops the last character of a. Moving left drops the last character of b. Either branch can still reach a full-length LCS, but the branches can produce different strings.
The tie-breaking rule decides which branch to follow at such a cell. The traceback from the tabulation chapter uses >=, so it prefers moving up whenever the values are equal.
The Same Table, Two Answers
Here is the full table for the running example. Rows are prefixes of a, columns are prefixes of b.
| Row | ε | B | D | C | A | B | A |
|---|---|---|---|---|---|---|---|
| ε | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| A | 0 | 0 | 0 | 0 | 1 | 1 | 1 |
| B | 0 | 1 | 1 | 1 | 1 | 2 | 2 |
| C | 0 | 1 | 1 | 2 | 2 | 2 | 2 |
| B | 0 | 1 | 1 | 2 | 2 | 3 | 3 |
| D | 0 | 1 | 2 | 2 | 2 | 3 | 3 |
| A | 0 | 1 | 2 | 2 | 3 | 3 | 4 |
| B | 0 | 1 | 2 | 2 | 3 | 4 | 4 |
The traceback starts at the bottom-right cell (row B, column A). The characters differ, and both neighbors hold 4. That cell is already a tie. With "prefer up" the walk produces BCBA. With "prefer left" it produces BDAB. Both have length 4, and both are correct.
The following program runs the traceback with each policy, so you can confirm this yourself.
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 traceback(a, b, dp, prefer_up=True):
out = []
i, j = len(a), len(b)
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
elif dp[i - 1][j] < dp[i][j - 1]:
j -= 1
elif prefer_up: # tie
i -= 1
else:
j -= 1
return "".join(reversed(out))
a, b = "ABCBDAB", "BDCABA"
dp = lcs_table(a, b)
print(traceback(a, b, dp, prefer_up=True)) # BCBA
print(traceback(a, b, dp, prefer_up=False)) # BDABEnumerating Every LCS
Sometimes you want all of them. Examples include showing a user every valid alignment, or checking whether the LCS is unique. To do that, follow every optimal move at a tie instead of picking one.
Matching cells need no branching. If a[i-1] == b[j-1], every LCS of those two prefixes ends with that character. Suppose one did not. It would use neither final character, and appending the shared character would give a longer common subsequence, which is impossible. So at a match you only move diagonally.
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']
print(all_lcs("abcdef", "badcfe")) # 8 strings of length 3
print(all_lcs("AC", "BD")) # ['']Two design choices in this code are worth noting.
- Sets, not lists. Moving up then left and moving left then up can reach the same cell. Both routes then generate identical strings. Counting traceback paths therefore overcounts the distinct answers. The inputs
"AC"and"BD"show this at the extreme: they share no characters, so many paths lead to the corner, but only one LCS exists, the empty string. - Caching
back(i, j). Without the cache, the same cell is re-expanded once for every path that reaches it. The cache stores each cell's set of strings once. It returnsfrozensetbecause cached values should not be mutable.
How Many Can There Be?
The number of distinct LCSs can grow exponentially with input length. Take k pairs of letters that are all different from each other. Write each pair in one order in a and reversed in b:
a = "ab" + "cd" + "ef"b = "ba" + "dc" + "fe"
Letters from different pairs never match, so a common subsequence can take at most one letter from each pair. The LCS length is k, and each pair offers two independent choices. That gives exactly 2^k distinct LCSs, which is 8 for the example above. With 20 pairs (strings of length 40) there are over a million.
| Task | Cost beyond the O(mn) table | Practical for large inputs? |
|---|---|---|
| Find the LCS length | Nothing extra | Yes |
| Recover one LCS | O(m + n) traceback | Yes |
| Test whether the LCS is unique | Branching traceback that stops at the second answer found | Usually |
| List every LCS | Proportional to the size of the output, which can be exponential | Only for small or low-ambiguity inputs |
The table itself is still O(mn). The cost explodes only because the output can be huge. Any algorithm that prints every answer must spend at least that much time.
Choosing a Policy on Purpose
Since some answer must be returned, pick the rule deliberately:
- Determinism. Fix the rule and document it, so the same inputs always give the same output. This matters for snapshot tests and reproducible reports.
- Readable alignments. In diff-style output, different tie choices group the insertions and deletions differently. One choice might produce a single block of changes, while another scatters the same changes across several places. Practical diff tools add heuristics on top of the plain LCS for this reason. The next chapters return to this.
- Consistency across implementations. If you later replace the full table with a linear-space method such as Hirschberg's algorithm, expect it to return a different, equally long LCS unless you take care to match the tie behavior.
Exercises
Exercise
In the traceback code, the tie case is reached only when the characters differ and dp[i-1][j] == dp[i][j-1]. Why does the enumeration function never branch at a cell where the characters match, even though dp[i-1][j] might also equal dp[i][j] there?
Show answer
When a[i-1] == b[j-1], every LCS of a[:i] and b[:j] ends with that shared character. Any common subsequence that ended otherwise would use neither final character, so appending the shared character would make it longer, which contradicts maximality. Moving up or left at such a cell can only rediscover strings that the diagonal move already produces, ending in the same character, so branching there adds work and finds nothing new.
Exercise
How many distinct LCSs do a = "abcdefgh" and b = "badcfehg" have, and what is their length?
Show answer
The strings form four letter pairs (ab, cd, ef, gh), and each pair is reversed in b. A common subsequence can take at most one letter per pair, so the LCS length is 4. Each pair offers two independent choices, giving 2^4 = 16 distinct LCSs.
Exercise
A colleague counts LCSs by counting traceback paths from the bottom-right cell to row 0 or column 0, following every optimal move. For a = "AC" and b = "BD" they report 6. What is the true count, and what causes the difference?
Show answer
The true count is 1, because the only LCS is the empty string. The two strings share no characters, so every cell is a tie and many monotone paths lead to the boundary, but each path emits nothing. Different paths can produce the same string, so path counts overcount distinct subsequences. Collecting strings in a set fixes this.