Sub topic 1
What Is a Subsequence?
This chapter defines the longest common subsequence (LCS) problem, shows why trying every option fails, and derives the recurrence that the rest of the tutorial builds on.
Prerequisites
This chapter assumes you know:
- Basic Python: lists, loops, and functions
- Recursion and base cases
- Big-O notation
- Lists of lists used as 2D arrays
Subsequences vs. Substrings
You get a subsequence by deleting zero or more characters from a sequence while keeping the remaining characters in their original order. A substring must also be contiguous.
| Sequence | Candidate | Subsequence? | Substring? |
|---|---|---|---|
| `ABCBDAB` | `BCB` | Yes | Yes |
| `ABCBDAB` | `ACDB` | Yes | No |
| `ABCBDAB` | `DBA` | No | No |
A common mistake is to treat "subsequence" and "substring" as the same thing. Gaps are allowed in a subsequence, but the order of the characters can never change.
The LCS Problem
Given sequences a of length m and b of length n, find the longest sequence that is a subsequence of both. For ABCBDAB and BDCABA, the LCS length is 4, and BCBA is one answer. There can be several answers with the same length, so the problem asks for a longest one.
Why Brute Force Does Not Scale
The direct approach lists every subsequence of a, from longest to shortest, and returns the first one that also appears in b.
from itertools import combinations
def is_subsequence(s, t):
it = iter(t)
return all(ch in it for ch in s)
def lcs_brute(a, b):
for k in range(len(a), -1, -1):
for idx in combinations(range(len(a)), k):
cand = "".join(a[i] for i in idx)
if is_subsequence(cand, b):
return cand
return ""
print(lcs_brute("ABCBDAB", "BDCABA")) # a length-4 LCSA sequence of length m has 2^m subsequences, and each check against b costs O(n), so the total is O(n · 2^m). With m = 50, that is about 10^15 candidates.
Optimal Substructure and the Recurrence
Let L(i, j) be the LCS length of the suffixes a[i:] and b[j:]. Look at the first characters of the two suffixes:
- If
a[i] == b[j], some LCS uses this match. Keep it and solve the rest: L(i, j) = 1 + L(i+1, j+1). - Otherwise, at least one of the two characters is not in the LCS. Drop one and try both choices: L(i, j) = max(L(i+1, j), L(i, j+1)).
- Base case: if either suffix is empty, L(i, j) = 0.
The optimal answer is built from optimal answers to smaller suffix pairs. This property is called optimal substructure, and it is what makes dynamic programming possible.
Exercise
Is "BDAB" a subsequence of "ABCBDAB"? Is it a substring? What is L(i, j) when a[i:] = "AB" and b[j:] = "B"?
Show answer
Yes and yes: "BDAB" is the last four characters of "ABCBDAB". For "AB" vs "B", 'A' does not equal 'B', so L = max(L("B","B"), L("AB","")) = max(1, 0) = 1.