How the longest common subsequence fills a grid

Short answer: The longest common subsequence of two strings is the longest sequence that appears in both, in order, not necessarily contiguously. The cell L[i][j] equals L[i−1][j−1] + 1 when the i-th and j-th characters match, and otherwise the maximum of L[i−1][j] and L[i][j−1]. The table is O(nm) time. The length is L[n][m], and one subsequence is recovered by walking from that cell back to the origin. Two rows suffice for the length.


What the problem actually asks

A subsequence may skip characters. The optimal match of two prefixes either pairs the last characters, which requires them to be equal, or discards the last character of one of the two strings. There is no substitution cost. A mismatch simply refuses the pair. That is the whole recurrence, and it is the Levenshtein recurrence with copies worth one and mismatches forbidden rather than charged.

Contiguous common substrings are a different and easier problem. A match there resets when the characters differ, and the answer is a maximum cell, not the corner. Mixing the two recurrences returns a substring length under a subsequence name.


What the algorithm guarantees

L[n][m] is the LCS length. Time is Θ(nm). The walk that emits a character whenever it takes the diagonal step recovers one LCS, reversed. Several LCS strings can exist. The length is unique. Space for the length alone is O(min(n, m)). Hirschberg’s technique recovers one subsequence in linear space, the same way it recovers an alignment.

The classical lower bound in the comparison model is quadratic for the general problem, so this table is the standard algorithm rather than a slow version of a linear one. Special cases, such as a permutation of 1..n against 1..n, reduce to a longest increasing subsequence and run in O(n log n). That reduction does not apply to arbitrary alphabets.


The working steps

  1. Set the first row and the first column to 0. An empty string has an empty common subsequence with everyone.
  2. If a[i] equals b[j], set L[i][j] = L[i−1][j−1] + 1. Otherwise set L[i][j] = max(L[i−1][j], L[i][j−1]).
  3. The length is L[n][m].
  4. Walk from (n, m). When the characters match and the cell equals the diagonal plus one, emit the character and step diagonally. Otherwise step to the neighbor whose value equals the current cell.
  5. For the length only, store two rows. For one subsequence in linear space, use the midpoint divide-and-conquer.

The quadratic bound is for two strings. A longest increasing subsequence of one sequence is the patience-sorting pile method, O(n log n). A longest common substring, contiguous, uses a different reset-to-zero recurrence or a suffix array. The LCS grid does not require the characters to sit next to each other.


Approaches that look simpler and fail

Approach Why it fails when a mismatch resets the cell to zero
Set the cell to 0 when the characters differ That computes a longest common substring, or a close relative of it. A subsequence may skip the mismatch and keep the length accumulated so far.
Add one on every diagonal, matched or not A substitution is not a common character. The diagonal step requires equality.
Recover the subsequence from the values alone, with no parent rule Equal values can come from either neighbor. The walk needs the match test, or an explicit predecessor, to know when to emit.
Quote O(n log n) for two general strings That bound is the patience method for a single sequence’s increasing subsequence. Two arbitrary strings use the quadratic table.

Unit-cost edit distance is the Levenshtein grid. Contiguous matches are longest common substring. One sequence’s increasing subsequence is patience sorting. LCS is the skip-allowed common sequence.


A working example

This Python fragment fills the longest-common-subsequence grid. A mismatch takes the best neighbor and does not reset the cell to zero. It prints 4 for ABCBD and ACBAD.

def lcs(a, b):
    prev = [0] * (len(b) + 1)
    for ca in a:
        cur = [0]
        for j, cb in enumerate(b, 1):
            if ca == cb:
                cur.append(prev[j - 1] + 1)
            else:
                cur.append(max(prev[j], cur[j - 1]))
        prev = cur
    return prev[-1]

assert lcs("ABCBD", "ACBAD") == 4
print(lcs("ABCBD", "ACBAD"))

Where it is used

The longest common subsequence is the dual of a diff: the lines two files still share, which is the comparison diff and Myers’ edit script answer. DNA tools ask the same question of two strings. A longest common substring is contiguous and is a different table.


When you can drop this algorithm

Drop the full table when only the length is required. Keep two rows. Drop the algorithm when the strings are a permutation pair and the O(n log n) reduction to LIS applies. Keep the grid for arbitrary alphabets when the subsequence, not the substring, is the object.


Why this stays published

We publish this so a search for the longest common subsequence returns the match-or-skip recurrence and the distinction from a contiguous substring. The longest common subsequence is the quadratic grid that adds one on a match and otherwise takes the better of the two prefixes with one character dropped.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *