Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 n×mn \times m 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 O((r+n)log⁡n)O((r + n)\log n) time for rr matching pairs.
  • Explain bit-parallel LCS and its O(⌈m/w⌉ n)O(\lceil m/w \rceil\, n) 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 (i,j)(i, j) a match if a[i]=b[j]a[i] = b[j], and let rr be the number of matches. A common subsequence of length ℓ\ell is exactly a chain of matches (i1,j1),…,(iℓ,jℓ)(i_1, j_1), \dots, (i_\ell, j_\ell) with i1<⋯<iℓi_1 < \dots < i_\ell and j1<⋯<jℓj_1 < \dots < j_\ell. So a longest common subsequence is a longest chain increasing in both coordinates: a longest increasing subsequence problem in disguise.

python
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 pairs

Checked 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 nm/2nm/2 matches, and O(nmlog⁡n)O(nm \log n) 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 O(ND)O(ND) 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.

Check your understanding

Why does Hunt–Szymanski feed each row's matching columns to the tails array in decreasing order?

  1. So that two matches of the same row, one letter of aa, can never both be used: in decreasing order they cannot form an increasing pair
  2. So that the binary searches run faster
  3. So that the subsequence comes out reversed
  4. It makes no difference; any order works
Show the answer

A. So that two matches of the same row, one letter of aa, can never both be used: in decreasing order they cannot form an increasing pair

A row is one letter of aa, which can be matched only once. Fed in increasing order, the matches (i,2)(i, 2) and (i,5)(i, 5) would extend each other and count a[i]a[i] twice. For a=Aa = \texttt{A} and b=AAb = \texttt{AA}, 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 mm-bit vector VV: a 0 bit marks a column where the row steps up, so the row's final value is the number of zero bits. Let McM_c be the match mask of letter cc, with bit jj set iff b[j]=cb[j] = c. 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:

U=V&Ma[i],V←(V+U)∣(V−U).U = V \mathbin{\&} M_{a[i]}, \qquad V \leftarrow (V + U) \mid (V - U).
python
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'))          # 4

Each row costs O(⌈m/w⌉)O(\lceil m/w \rceil) word operations, with the addition's carry passed from word to word: O(⌈m/w⌉ n)O(\lceil m/w \rceil\, n) in all, one 64-bit word per letter of aa when m≤64m \le 64. 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: nm/wnm/w word operations instead of nmnm cell updates. Given the conditional lower bound in the next step, that factor of ww, 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 kk strings of length nn the table generalizes directly: a state is a kk-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 (n+1)k(n + 1)^k states with O(k)O(k) work each, polynomial for every fixed kk but hopeless beyond a few strings. With kk part of the input, no polynomial algorithm is expected at all:

DerivationA reduction from independent set (with a large alphabet)
  1. suv=(1⋯n without u) (1⋯n without v)s_{uv} = \big(1 \cdots n \text{ without } u\big)\ \big(1 \cdots n \text{ without } v\big)

    Take a graph with vertices 1,…,n1, \dots, n and use the vertices as letters. Let s0=1 2⋯ns_0 = 1\,2 \cdots n, and for every edge {u,v}\{u, v\} with u<vu < v let suvs_{uv} be s0s_0 with uu removed, followed by s0s_0 with vv removed. A common subsequence of all the strings is a subsequence of s0s_0: a set of vertices, listed in increasing order.

  2. S embeds in suv  ⟺  {u,v}⊈SS \text{ embeds in } s_{uv} \iff \{u, v\} \not\subseteq S

    A set SS that contains both uu and vv cannot be embedded in suvs_{uv}: uu occurs only in the second half, and vv, which must come after uu, does not occur after it. A set with at most one of them embeds: entirely in the first half if it avoids uu, entirely in the second if it avoids vv.

  3. LCS(s0, suv:{u,v}∈E)=α(G)\mathrm{LCS}\big(s_0,\ s_{uv} : \{u, v\} \in E\big) = \alpha(G)

    So the common subsequences are exactly the independent sets, and the LCS length is the size α(G)\alpha(G) of a maximum independent set, which is NP-hard to compute. The strings have total length O(n ∣E∣)O(n\,\abs E). 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 nn has no O(n2−δ)O(n^{2-\delta}) algorithm for any δ>0\delta > 0 (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).

VariantBest knownStatus
Two stringsO(nm)O(nm), or O(nm/w)O(nm/w) word operationsNo O(n2−δ)O(n^{2-\delta}) under SETH
Two strings with rr matching pairsO((r+n)log⁡n)O((r + n)\log n)Fast when matches are rare
Two permutationsO(nlog⁡n)O(n \log n), as an LISOptimal among comparison algorithms
kk strings, kk fixedO(k nk)O(k\,n^k)Polynomial for each fixed kk
Any number of stringsExponentialNP-hard, even over {0,1}\{0, 1\} (Maier, 1978)
The complexity of LCS depends on what is fixed: the number of strings, the number of matches, or the structure of the input.

Random strings: the Chvátal–Sankoff constant

How long is the LCS of two random strings? Let LnL_n be the LCS length of two independent, uniformly random binary strings of length nn.

DerivationProof: superadditivity
  1. Ln+m ≥ Ln′+Lm′′L_{n+m}\ \ge\ L'_n + L''_m

    Split each of two strings of length n+mn + m into a first part of length nn and a second part of length mm. An LCS of the two first parts followed by an LCS of the two second parts is a common subsequence of the whole strings:

  2. E[Ln+m] ≥ E[Ln]+E[Lm]\mathbb E[L_{n+m}]\ \ge\ \mathbb E[L_n] + \mathbb E[L_m]

    The two pairs of parts are independent random strings of lengths nn and mm, so taking expectations gives superadditivity:

  3. γ2=lim⁡n→∞E[Ln]n=sup⁡nE[Ln]n ≤ 1\gamma_2 = \lim_{n \to \infty} \frac{\mathbb E[L_n]}{n} = \sup_n \frac{\mathbb E[L_n]}{n}\ \le\ 1

    By Fekete's lemma, xn/nx_n/n converges to sup⁡nxn/n\sup_n x_n/n for every superadditive sequence xnx_n, and here xn/n≤1x_n/n \le 1, so the limit is finite:

The value itself is unknown. Lueker (2009) proved 0.788071≤γ2≤0.8262800.788071 \le \gamma_2 \le 0.826280 with computer-assisted bounds, the lower bound has since been raised to about 0.79270.7927 (Heineman et al., 2024), and numerical estimates put γ2\gamma_2 near 0.8120.812. Because the limit is a supremum, finite strings approach it from below: in a quick simulation, the average of Ln/nL_n/n was about 0.7800.780 for n=100n = 100, 0.8060.806 for n=1000n = 1000 and 0.8090.809 for n=4000n = 4000.

Predict before you look

Two random binary strings have 10,000 characters each. About how long is their LCS?

Show the answer

8100

γ2≈0.81\gamma_2 \approx 0.81, so about 8,100; finite lengths sit slightly below the limit (about 0.809 at n=4000n = 4000 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 n/2n/2 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: O((r+n)log⁡n)O((r + n)\log n), 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 V←(V+U)∣(V−U)V \leftarrow (V + U) \mid (V - U) handles ww cells per word operation.
  • Two strings: polynomial, but no O(n2−δ)O(n^{2-\delta}) 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, E[Ln]/n→γ2\mathbb E[L_n]/n \to \gamma_2 by superadditivity and Fekete's lemma; 0.7927≲γ2≤0.82630.7927 \lesssim \gamma_2 \le 0.8263, 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.

Question 1

For which inputs is Hunt–Szymanski's O((r+n)log⁡n)O((r + n)\log n) much faster than the O(nm)O(nm) table?

  1. Two random binary strings
  2. Two files whose lines are mostly distinct, so that few pairs of lines match
  3. Any two strings: it is never slower
  4. 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 rr of matching pairs. Distinct lines rarely match, so rr stays close to nn. Binary strings match about half the time, so r≈nm/2r \approx nm/2 and O(nmlog⁡n)O(nm \log n) loses to the table.

Question 2

How fast can the LCS of two permutations of {1,…,n}\{1, \dots, n\} be computed?

  1. O(n2)O(n^2), and no faster
  2. O(nlog⁡n)O(n \log n): every element matches exactly once, so the LCS is an LIS
  3. O(n)O(n), by merging the two permutations
  4. It is NP-hard
Show the answer

B. O(nlog⁡n)O(n \log n): every element matches exactly once, so the LCS is an LIS

Relabel the second permutation as 1,2,…,n1, 2, \dots, n; the LCS becomes a longest increasing subsequence of the relabeled first permutation. Equivalently, Hunt–Szymanski with r=nr = n matching pairs runs in O(nlog⁡n)O(n \log n).

Question 3

Which version of the LCS problem is NP-hard?

  1. Two strings over a binary alphabet
  2. Three strings of length nn
  3. Any number of strings, given as part of the input, even over a binary alphabet
  4. 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 kk of strings, the kk-dimensional table runs in polynomial time, O(k nk)O(k\,n^k).

Question 4

What is known about the Chvátal–Sankoff constant γ2\gamma_2?

  1. γ2=2/(1+2)≈0.828\gamma_2 = 2/(1 + \sqrt 2) \approx 0.828, proved in 1975
  2. The limit exists by superadditivity, its value lies between about 0.79 and 0.83, and its exact value is unknown
  3. γ2=1/2\gamma_2 = 1/2, since each position agrees with probability 1/21/2
  4. The limit does not exist: E[Ln]/n\mathbb E[L_n]/n 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.