Sub topic 2
Stating the Longest Common Subsequence Problem
This chapter turns the informal idea of "what two sequences have in common" into a precise problem. It assumes you can read basic Python (lists, loops, functions) and that you already know what a subsequence is from the previous chapter. Later chapters depend on the vocabulary and notation set up here: prefixes, witnesses, and the bounds on the answer.
The Formal Statement
Take two finite sequences:
X = x1 x2 ... xmof lengthmY = y1 y2 ... ynof lengthn
A sequence Z is a common subsequence of X and Y if it is a subsequence of both. The longest common subsequence (LCS) problem asks for a common subsequence of maximum length.
You can phrase the same idea in terms of positions. A common subsequence of length k corresponds to two lists of indices:
i1 < i2 < ... < ikinXj1 < j2 < ... < jkinY
with x[i_t] == y[j_t] for every t. This pairing of positions is called a witness. To prove a claimed common subsequence is valid, you show its witness: matched pairs that are strictly increasing in both sequences.
The Running Example
The rest of this tutorial uses the same pair of strings throughout:
a = "ABCBDAB"(m = 7)b = "BDCABA"(n = 6)
Their LCS has length 4. Several different strings reach that length, including BCBA, BDAB, and BCAB. Here is the witness for BCBA, with zero-based indices:
| LCS symbol | Index in `a` | Index in `b` |
|---|---|---|
| B | 1 | 0 |
| C | 2 | 2 |
| B | 3 | 4 |
| A | 5 | 5 |
Both index columns are strictly increasing, and each row pairs equal symbols.
Checking a Candidate
Finding an LCS is the hard part. Checking whether a proposed answer is a common subsequence is easy. The code below does both kinds of check: one on the subsequence itself, and one on an explicit witness.
def is_subsequence(s, t):
"""True if s is a subsequence of t. Works for strings or lists."""
it = iter(t)
# 'x in it' advances the iterator past the first match, so
# each element of s must be found after the previous one.
return all(x in it for x in s)
def is_common_subsequence(z, a, b):
return is_subsequence(z, a) and is_subsequence(z, b)
def check_witness(a, b, pairs):
"""pairs is a list of (i, j) index pairs. Returns the matched sequence
if the witness is valid, otherwise raises ValueError."""
prev_i, prev_j = -1, -1
out = []
for i, j in pairs:
if not (prev_i < i < len(a) and prev_j < j < len(b)):
raise ValueError(f"pair {(i, j)} is out of order or out of range")
if a[i] != b[j]:
raise ValueError(f"a[{i}]={a[i]!r} != b[{j}]={b[j]!r}")
out.append(a[i])
prev_i, prev_j = i, j
return out
a, b = "ABCBDAB", "BDCABA"
for z in ["BCBA", "BDAB", "BCAB", "ABBA", "BDCABA"]:
print(z, is_common_subsequence(z, a, b))
print("".join(check_witness(a, b, [(1, 0), (2, 2), (3, 4), (5, 5)])))Running it prints:
BCBA True
BDAB True
BCAB True
ABBA False
BDCABA False
BCBAABBA fails because b has only one B after its first A. BDCABA is all of b, but it is not a subsequence of a, since a has no A after its D that is followed by B and then A.
What Exactly Is the Output?
"Solve LCS" can mean any of several related problems. Be clear about which one you are solving, because they cost different amounts.
| Variant | Output | Notes |
|---|---|---|
| Length | A single integer `k` | The cheapest version. Covered by the two-row method later. |
| One LCS | One sequence of length `k` | Needs traceback or Hirschberg's method. |
| All LCSs | Every distinct sequence of length `k` | The number of distinct answers can grow exponentially, so the output alone can be huge. |
| Decision | Yes/no: is there a common subsequence of length at least `k`? | The form used in complexity theory. |
This tutorial focuses on the first two. When an answer is not unique, the algorithms return one of the valid answers, and which one depends on tie-breaking. A later chapter covers that.
Properties That Hold for Every Input
These facts are worth knowing before you write any algorithm. They make good sanity checks for your code.
- Bounds.
0 <= LCS(X, Y) <= min(m, n). A common subsequence cannot be longer than either input. - Symmetry.
LCS(X, Y)andLCS(Y, X)have the same length, and the same set of answers. - Empty input. If either sequence is empty, the LCS is empty and its length is 0.
- Identical inputs.
LCS(X, X) = X. - Containment. If
Xis a subsequence ofY, thenLCS(X, Y) = X, and the length reaches the upper boundmin(m, n). - Disjoint alphabets. If no symbol occurs in both, the length is 0.
- Monotonicity. Appending elements to either input never shortens the LCS.
Prefix notation
The solution methods all work on prefixes. Write X_i for the first i elements of X, so X_0 is empty and X_m = X. Define L(i, j) as the LCS length of X_i and Y_j. The answer to the full problem is L(m, n), and the base cases L(0, j) = L(i, 0) = 0 follow from the empty-input property. The recurrence chapter derives how L(i, j) relates to smaller prefixes. For now, L(i, j) just names the quantity we want.
Sequences Are Not Only Strings
Strings are the usual examples, but nothing in the definition requires characters. Any two sequences whose elements can be tested for equality will work:
- lines of two files (the basis of
diff) - tokens of two programs
- DNA bases or protein residues
- lists of event IDs from two logs
The meaning of "equal" belongs to the problem. If you compare lines but ignore trailing whitespace or letter case, you have to normalize the elements before running LCS. The algorithm will not do it for you.
old = ["def f(x):", " return x + 1", ""]
new = ["def f(x):", " # increment", " return x + 1", ""]
print(is_subsequence(old, new)) # True: every old line survives, in orderCommon Mistakes When Stating the Problem
Confusing it with longest common substring
A substring must be contiguous, and a subsequence need not be. For our example, the longest common substring of ABCBDAB and BDCABA has length 2 (for example AB or BD), while the LCS has length 4. A later chapter covers the substring problem, which uses a different recurrence.
Assuming the answer is unique
Code that checks lcs(a, b) == "BCBA" is fragile. A correct implementation may return BDAB instead. Test the length, and test that the result is a common subsequence.
Assuming greedy matching works
A tempting shortcut is to walk through X and match each element to its earliest occurrence in Y that comes after the previous match. This can lock in an early match that blocks better ones later:
def greedy_common(a, b):
out, j = [], 0
for x in a:
k = b.find(x, j)
if k != -1:
out.append(x)
j = k + 1
return "".join(out)
print(greedy_common("CAB", "ABC")) # "C", length 1
print(is_common_subsequence("AB", "CAB", "ABC")) # True, length 2Greedy matches C to the last position of ABC, which leaves nothing for A or B. The correct answer skips C. Deciding what to skip requires weighing alternatives, and dynamic programming does that systematically.
Exercises
Exercise
Give a valid witness (list of zero-based index pairs) showing that "BDAB" is a common subsequence of a = "ABCBDAB" and b = "BDCABA".
Show answer
[(1, 0), (4, 1), (5, 3), (6, 4)]. In a: B at 1, D at 4, A at 5, B at 6. In b: B at 0, D at 1, A at 3, B at 4. Both index lists are strictly increasing and each pair matches equal symbols.
Exercise
Without running any algorithm, state the LCS length of each pair: (1) "" and "XYZ"; (2) "ACE" and "ABCDE"; (3) "ABC" and "XYZ"; (4) "HELLO" and "HELLO".
Show answer
(1) 0, because one input is empty. (2) 3, because "ACE" is a subsequence of "ABCDE" (containment). (3) 0, because the alphabets are disjoint. (4) 5, because the inputs are identical.
Exercise
Find two strings where greedy_common returns a shorter result than the true LCS, other than the "CAB"/"ABC" example. Explain why greedy fails on them.
Show answer
One example is a = "BAB", b = "ABB" (other answers are possible). Greedy matches the first B of a to b[1], then finds no A after it, then matches the last B to b[2], which gives "BB" of length 2. That ties the LCS here, so try a = "BAA", b = "AAB": greedy matches B to b[2] and then cannot match either A, so it returns "B" (length 1), while "AA" has length 2. Greedy fails because committing to the earliest match for the current element can use up positions that later elements needed.
Exercise
Why can the "all LCSs" variant not run in polynomial time in general, even with a fast algorithm?
Show answer
The number of distinct longest common subsequences can grow exponentially with the input length. Writing out every answer would already take exponential time, whatever algorithm produced them.