Sub topic 10
LIS as a Longest Common Subsequence
This chapter assumes you know the O(n^2) LIS dynamic program and the O(n log n) tails-array method from earlier chapters. It also assumes you have seen the classic longest common subsequence (LCS) table, or can follow one as it is built here. Two problems are connected here. Any LIS problem can be rewritten as an LCS problem, and some LCS problems can be rewritten as LIS problems. The second direction is the one with practical value, because it turns a quadratic algorithm into an O(n log n) one.
The Longest Common Subsequence Problem
A common subsequence of two sequences x and y is a sequence that is a subsequence of both. The longest common subsequence is the longest such sequence. For x = "ABCBDAB" and y = "BDCABA", one LCS is "BCBA", with length 4.
The standard dynamic program fills a table where dp[i][j] is the LCS length of the first i items of x and the first j items of y:
- If
x[i-1] == y[j-1], thendp[i][j] = dp[i-1][j-1] + 1. - Otherwise,
dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
The table has (m+1) * (n+1) cells and each takes O(1) work, so time is O(mn).
The Reduction: LIS(a) = LCS(a, sorted distinct a)
Sort the distinct values of a into a new sequence s. Then the strict LIS of a has the same length as the LCS of a and s.
The argument goes in both directions.
- Every common subsequence is increasing. A common subsequence of
aandsis a subsequence ofs. Sincesis strictly increasing, so is anything taken from it in order. It is also a subsequence ofa, so it is a strictly increasing subsequence ofa. - Every strictly increasing subsequence is common. Take a strictly increasing subsequence of
a. Its values are distinct and appear in ascending order. Each of them occurs ins, andslists them in ascending order, so the subsequence also appears ins.
The two sets of sequences are the same set. Their longest members therefore have the same length.
Implementation
def lcs_length(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[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[m][n]
def lis_via_lcs(a):
return lcs_length(a, sorted(set(a)))
print(lis_via_lcs([10, 9, 2, 5, 3, 7, 101, 18])) # 4
print(lis_via_lcs([])) # 0
print(lis_via_lcs([5, 5, 5])) # 1For [10, 9, 2, 5, 3, 7, 101, 18], s is [2, 3, 5, 7, 9, 10, 18, 101]. Both [2, 5, 7, 101] and [2, 3, 7, 18] are common subsequences of length 4. This matches the answer from the direct LIS algorithms.
Recovering the Subsequence
The LCS table can be walked backwards from dp[m][n] to recover one optimal sequence. Every matched pair you step through diagonally adds one element.
def lcs_sequence(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[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 x[i - 1] == y[j - 1]:
out.append(x[i - 1])
i -= 1
j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1
else:
j -= 1
return out[::-1]
a = [10, 9, 2, 5, 3, 7, 101, 18]
seq = lcs_sequence(a, sorted(set(a)))
assert len(seq) == 4
assert all(p < q for p, q in zip(seq, seq[1:]))
print(seq) # one strictly increasing subsequence of length 4The tie-breaking rule in the elif branch decides which of several optimal answers you get. Changing >= to > can return a different, equally long subsequence.
Strict vs Non-Decreasing Through the Same Lens
The choice of s sets which variant you compute:
| Second sequence `s` | What LCS(a, s) computes | Why |
|---|---|---|
| `sorted(set(a))` | Longest strictly increasing subsequence | `s` has no repeats, so a common subsequence cannot repeat a value |
| `sorted(a)` | Longest non-decreasing subsequence | `s` keeps every copy, so equal values can be matched repeatedly |
def lcs_length(x, y):
m, n = len(x), len(y)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if x[i - 1] == y[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[m][n]
a = [1, 3, 3, 2, 3]
print(lcs_length(a, sorted(set(a)))) # 2 (strict: e.g. [1, 3])
print(lcs_length(a, sorted(a))) # 4 (non-decreasing: [1, 3, 3, 3])This matches the bisect_left versus bisect_right distinction from the earlier chapter. Here the duplicates in the second sequence control the behavior instead of the choice of search bound.
Cost of the Reduction
The LCS route costs O(n^2) time, the same as the direct quadratic LIS DP, plus O(n log n) for sorting. The full table needs O(n^2) memory. If you only need the length, keep two rows and memory falls to O(n):
def lcs_length_two_rows(x, y):
prev = [0] * (len(y) + 1)
for xi in x:
cur = [0] * (len(y) + 1)
for j, yj in enumerate(y, start=1):
if xi == yj:
cur[j] = prev[j - 1] + 1
else:
cur[j] = max(prev[j], cur[j - 1])
prev = cur
return prev[-1]
a = [10, 9, 2, 5, 3, 7, 101, 18]
print(lcs_length_two_rows(a, sorted(set(a)))) # 4As a way to compute LIS, the reduction is never faster than the direct methods. Its value lies elsewhere. It proves that LIS is a special case of LCS. It lets you reuse an LCS routine you already trust. It also points toward the reverse reduction.
The Reverse Direction: LCS of Permutations via LIS
Suppose p and q are permutations of the same set of distinct items. Replace each item in p with its position in q. A common subsequence of p and q is a run of items in p whose positions in q increase. So the LCS of p and q equals the strict LIS of that list of positions, and the O(n log n) tails method computes it.
from bisect import bisect_left
def lis_length(a):
tails = []
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
def lcs_distinct(p, q):
pos = {v: i for i, v in enumerate(q)}
mapped = [pos[v] for v in p if v in pos] # drop items missing from q
return lis_length(mapped)
print(lcs_distinct([3, 1, 2, 5, 4], [1, 2, 3, 4, 5])) # 3
print(lcs_distinct(list("EBDAC"), list("ABCDE"))) # 2In the first call, mapped is [2, 0, 1, 4, 3], and its LIS [0, 1, 3] corresponds to the items 1, 2, 4. Filtering out items absent from q lets the function also handle inputs that only have distinct items within each sequence, rather than exact permutations.
Handling Repeats: The Hunt-Szymanski Idea
When items repeat, one item of x can match several positions in y. For each item of x, list all of its positions in y in descending order, then join those lists together. The strict LIS of the result is the LCS length.
The descending order prevents a single item of x from being matched to two positions of y. Inside one item's block the positions decrease, so a strictly increasing subsequence can take at most one of them. This is the same trick the envelope problem uses when it sorts heights in descending order for equal widths.
from bisect import bisect_left
from collections import defaultdict
def lis_length(a):
tails = []
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
def lcs_hunt_szymanski(x, y):
where = defaultdict(list)
for j, v in enumerate(y):
where[v].append(j)
seq = []
for v in x:
seq.extend(reversed(where[v])) # descending positions
return lis_length(seq)
print(lcs_hunt_szymanski("ABCBDAB", "BDCABA")) # 4If r is the number of matching pairs (i, j) with x[i] == y[j], the running time is O(r log n). When matches are sparse, as in comparing lines of two source files, this is much faster than O(mn). When matches are dense, r approaches mn and the method is slower than the plain table. Two strings over a small alphabet such as DNA show this worst case.
Choosing an Approach
| Situation | Method | Time |
|---|---|---|
| Need LIS, any input | Tails array with binary search | O(n log n) |
| Need LIS, only an LCS routine available | LCS with `sorted(set(a))` | O(n^2) |
| LCS of two sequences of distinct items | Map to positions, then LIS | O(n log n) |
| LCS with repeats, few matching pairs | Hunt-Szymanski | O(r log n) |
| LCS with repeats, many matching pairs | Standard LCS table | O(mn) |
Common Errors
- Using
bisect_rightin the reverse reduction. Positions inmappedare distinct, so this makes no difference in the permutation case. In Hunt-Szymanski it allows two equal positions to chain. That cannot happen with distinct positions per block either, but the strict LIS is the correct model, so usebisect_left. - Ascending positions per block. If you list positions in ascending order, one item of
xcan match several items ofy. The result overcounts:lcs_hunt_szymanski("A", "AAA")would return 3 instead of 1. - Forgetting items missing from the other sequence.
pos[v]raisesKeyErrorifvis not inq. Filter those items out first, because they can never be part of a common subsequence.
Exercise
For a = [4, 1, 4, 2, 3], compute LCS(a, sorted(set(a))) and LCS(a, sorted(a)) by reasoning about subsequences, and say which LIS variant each one gives.
Show answer
sorted(set(a)) = [1, 2, 3, 4]. The longest common subsequence is [1, 2, 3], length 3, which is the strict LIS. sorted(a) = [1, 2, 3, 4, 4]. Its longest common subsequence with a is also length 3 (for example [1, 2, 3]). No non-decreasing subsequence of length 4 exists, because [4, 4] cannot be extended and nothing longer than [1, 2, 3] is ordered. Both variants give 3 here, since the duplicate 4s cannot sit in the same chain as the smaller values that follow them.
Exercise
Why does Hunt-Szymanski list each item's positions in y in descending order? Give a small input where ascending order produces a wrong answer.
Show answer
Inside one block the positions strictly decrease, so a strictly increasing subsequence can use at most one position per item of x. That means each item of x is matched at most once. With ascending order, x = "A" and y = "AA" give the sequence [0, 1], whose LIS is 2. The true LCS is 1.
Exercise
Two sequences p and q each contain 100,000 distinct user IDs, and most IDs appear in both. Which method computes their LCS fastest, and what is its complexity?
Show answer
Map each ID in p to its index in q, drop the IDs that q does not contain, and run the O(n log n) tails-array LIS on the result. The total cost is O(n log n), roughly 1.7 million basic steps, compared with 10^10 table cells for the standard LCS DP.