Longest Common Subsequence in Depth
Hunt–Szymanski, bit-parallel LCS, and why many strings make it NP-hard.
The Unix diff of the 1970s compared files of thousands of lines on machines where an table was out of the question. Its secret was that most pairs of lines never match, and the Hunt–Szymanski algorithm works only on the pairs that do. This lesson takes the longest common subsequence beyond the table: algorithms that pay for matches rather than cells, bit-parallel LCS, a conditional quadratic barrier for two strings, NP-hardness for many, and a constant about random strings that nobody has determined.
What you’ll learn
- Reduce LCS to a longest chain of matching pairs, and implement Hunt–Szymanski in time for matching pairs.
- Explain bit-parallel LCS and its word operations.
- State the conditional quadratic lower bound for two strings, and prove that the LCS of many strings is NP-hard by a reduction from independent set.
- Prove that the Chvátal–Sankoff constant exists, and state what is known about its value.
LCS as a chain of matches
Call a match if , and let be the number of matches. A common subsequence of length is exactly a chain of matches with and . So a longest common subsequence is a longest chain increasing in both coordinates: a longest increasing subsequence problem in disguise.
from bisect import bisect_left
from collections import defaultdict
def hunt_szymanski(a, b):
"""LCS length in O((r + n) log n), r = number of matching pairs."""
where = defaultdict(list) # letter -> its positions in b
for j, y in enumerate(b):
where[y].append(j)
tails = [] # LIS tails over matched columns
for x in a:
for j in reversed(where[x]): # decreasing: one match per row at most
k = bisect_left(tails, j)
if k == len(tails):
tails.append(j)
else:
tails[k] = j
return len(tails)
print(hunt_szymanski('CARTOON', 'ACTION')) # 4, from r = 6 matching pairsChecked against the table on thousands of random strings. Predecessor pointers, as in the LIS lesson, recover the subsequence itself.
The bound is excellent when matches are rare and poor when they are dense: two random binary strings have about matches, and loses to the table. Lines of text are the rare-match case, which is why Hunt and McIlroy's 1976 diff used this idea. Myers's algorithm (1986), which explores the edit graph diagonal by diagonal and is fast when two files differ little, became the basis of GNU diff and of Git's default diff.
Why does Hunt–Szymanski feed each row's matching columns to the tails array in decreasing order?
- So that two matches of the same row, one letter of , can never both be used: in decreasing order they cannot form an increasing pair
- So that the binary searches run faster
- So that the subsequence comes out reversed
- It makes no difference; any order works
Show the answer
A. So that two matches of the same row, one letter of , can never both be used: in decreasing order they cannot form an increasing pair
A row is one letter of , which can be matched only once. Fed in increasing order, the matches and would extend each other and count twice. For and , increasing order reports length 2 instead of 1.
Bit-parallel LCS
Along a row of the LCS table, values rise by 0 or 1 per column, so a row is determined by the columns where it rises. Store their complement as an -bit vector : a 0 bit marks a column where the row steps up, so the row's final value is the number of zero bits. Let be the match mask of letter , with bit set iff . Allison and Dix (1986) showed that the next row follows from a few bitwise operations and one addition, whose carries propagate "the maximum of up and left" along the row; Hyyrö (2004) needs only four operations per row:
from collections import defaultdict
def lcs_bits(a, b):
"""LCS length with Hyyro's 4-operation row update; Python ints serve as bit vectors."""
m = len(b)
full = (1 << m) - 1
match = defaultdict(int) # match[c]: bit j set iff b[j] == c
for j, y in enumerate(b):
match[y] |= 1 << j
V = full # all ones: no step yet
for x in a:
U = V & match[x]
V = ((V + U) | (V - U)) & full
return m - bin(V).count('1') # LCS = number of zero bits
print(lcs_bits('CARTOON', 'ACTION')) # 4Each row costs word operations, with the addition's carry passed from word to word: in all, one 64-bit word per letter of when . Checked against the table on thousands of random strings, including 500-letter DNA strings.
Bit parallelism does not change the number of cells, only how many are processed per instruction: word operations instead of cell updates. Given the conditional lower bound in the next step, that factor of , together with the logarithmic Four-Russians speedup, is the realistic way to beat the plain table in the worst case.
Many strings: from tables to NP-hardness
For strings of length the table generalizes directly: a state is a -tuple of prefix lengths, and either all the last letters agree (step diagonally and add 1) or one string drops its last letter. That is states with work each, polynomial for every fixed but hopeless beyond a few strings. With part of the input, no polynomial algorithm is expected at all:
Take a graph with vertices and use the vertices as letters. Let , and for every edge with let be with removed, followed by with removed. A common subsequence of all the strings is a subsequence of : a set of vertices, listed in increasing order.
A set that contains both and cannot be embedded in : occurs only in the second half, and , which must come after , does not occur after it. A set with at most one of them embeds: entirely in the first half if it avoids , entirely in the second if it avoids .
So the common subsequences are exactly the independent sets, and the LCS length is the size of a maximum independent set, which is NP-hard to compute. The strings have total length . Maier's proof reaches the same conclusion with only two letters.
For two strings the obstacle is quantitative rather than NP-hardness. Under SETH, the LCS of two strings of length has no algorithm for any (Abboud, Backurs & Vassilevska Williams, FOCS 2015), even for binary strings (Bringmann & Künnemann, FOCS 2015), by reductions from orthogonal vectors like the one for edit distance. Later work extended these conditional bounds to parameters such as the number of matching pairs (Bringmann & Künnemann, 2018).
| Variant | Best known | Status |
|---|---|---|
| Two strings | , or word operations | No under SETH |
| Two strings with matching pairs | Fast when matches are rare | |
| Two permutations | , as an LIS | Optimal among comparison algorithms |
| strings, fixed | Polynomial for each fixed | |
| Any number of strings | Exponential | NP-hard, even over (Maier, 1978) |
Random strings: the Chvátal–Sankoff constant
How long is the LCS of two random strings? Let be the LCS length of two independent, uniformly random binary strings of length .
Split each of two strings of length into a first part of length and a second part of length . An LCS of the two first parts followed by an LCS of the two second parts is a common subsequence of the whole strings:
The two pairs of parts are independent random strings of lengths and , so taking expectations gives superadditivity:
By Fekete's lemma, converges to for every superadditive sequence , and here , so the limit is finite:
The value itself is unknown. Lueker (2009) proved with computer-assisted bounds, the lower bound has since been raised to about (Heineman et al., 2024), and numerical estimates put near . Because the limit is a supremum, finite strings approach it from below: in a quick simulation, the average of was about for , for and for .
Two random binary strings have 10,000 characters each. About how long is their LCS?
Show the answer
8100
, so about 8,100; finite lengths sit slightly below the limit (about 0.809 at in the simulation). The proven bounds on the limit, about 0.793 and 0.826, bracket the answer as well. An LCS can skip letters in both strings, which is why it is far longer than the positions where the two strings happen to agree.
Key takeaways
- An LCS is a longest chain of matching pairs increasing in both coordinates. Hunt–Szymanski feeds each row's matches, in decreasing column order, to an LIS computation: , excellent when matches are rare, as for lines of text.
- Rows of the LCS table step by 0 or 1, so they fit in bit vectors: one addition propagates the row's maxima, and Hyyrö's update handles cells per word operation.
- Two strings: polynomial, but no algorithm under SETH, even for binary strings. Any number of strings: NP-hard (Maier, 1978), as a reduction from independent set shows.
- For random binary strings, by superadditivity and Fekete's lemma; , and its exact value is open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For which inputs is Hunt–Szymanski's much faster than the table?
- Two random binary strings
- Two files whose lines are mostly distinct, so that few pairs of lines match
- Any two strings: it is never slower
- Two strings that differ in only a few places
Show the answer
B. Two files whose lines are mostly distinct, so that few pairs of lines match
The running time grows with the number of matching pairs. Distinct lines rarely match, so stays close to . Binary strings match about half the time, so and loses to the table.
How fast can the LCS of two permutations of be computed?
- , and no faster
- : every element matches exactly once, so the LCS is an LIS
- , by merging the two permutations
- It is NP-hard
Show the answer
B. : every element matches exactly once, so the LCS is an LIS
Relabel the second permutation as ; the LCS becomes a longest increasing subsequence of the relabeled first permutation. Equivalently, Hunt–Szymanski with matching pairs runs in .
Which version of the LCS problem is NP-hard?
- Two strings over a binary alphabet
- Three strings of length
- Any number of strings, given as part of the input, even over a binary alphabet
- Two permutations
Show the answer
C. Any number of strings, given as part of the input, even over a binary alphabet
Maier (1978) proved NP-completeness when the number of strings is part of the input, even with two letters. For every fixed number of strings, the -dimensional table runs in polynomial time, .
What is known about the Chvátal–Sankoff constant ?
- , proved in 1975
- The limit exists by superadditivity, its value lies between about 0.79 and 0.83, and its exact value is unknown
- , since each position agrees with probability
- The limit does not exist: oscillates
Show the answer
B. The limit exists by superadditivity, its value lies between about 0.79 and 0.83, and its exact value is unknown
Superadditivity and Fekete's lemma give existence. Computer-assisted bounds (Lueker, 2009, with the lower bound improved in 2024) place it between about 0.7927 and 0.8263, numerical estimates suggest about 0.812, but no exact value or closed form is known.
Further reading
- J. W. Hunt & T. G. Szymanski, "A fast algorithm for computing longest common subsequences," Communications of the ACM 20(5) (1977), 350–353.
- L. Allison & T. I. Dix, "A bit-string longest-common-subsequence algorithm," Information Processing Letters 23 (1986), 305–310.
- D. Maier, "The complexity of some problems on subsequences and supersequences," Journal of the ACM 25(2) (1978), 322–336.
- K. Bringmann & M. Künnemann, "Quadratic conditional lower bounds for string problems and dynamic time warping," FOCS 2015.
- V. Chvátal & D. Sankoff, "Longest common subsequences of two random sequences," Journal of Applied Probability 12 (1975), 306–315.