Simple Algorithm
Algorithms & Data Structures · Optimized · 24 min

Sequence DP: LIS, LCS & Edit Distance

Comparing and ordering sequences one table cell at a time.

Every time you run git diff, an algorithm finds a shortest edit script between two versions of a file. Every spell checker that suggests "receive" for "recieve" measures an edit distance, and genome aligners descend from the same table. This lesson builds the three classic sequence DPs, the longest increasing subsequence, the longest common subsequence and the edit distance, and teaches you to spot them in disguise.

What you’ll learn

  • Compute a longest increasing subsequence with the O(n2)O(n^2) DP and predecessor pointers, and its length in O(nlog⁡n)O(n \log n) with the tails array.
  • Fill and trace back LCS and edit-distance tables, and prove the edit-distance recurrence from the last column of an alignment.
  • Adapt the recurrences to weighted and local alignment, the longest common substring, the longest palindromic subsequence and the shortest common supersequence.
  • Recognize sequence-DP problems, choose between quadratic and O(nlog⁡n)O(n \log n) methods from the constraints, and avoid the classic bugs.

Longest increasing subsequence

A subsequence keeps elements in their original order but may skip some. A longest increasing subsequence (LIS) of a[0..n−1]a[0..n-1] is one whose elements strictly increase. Brute force checks all 2n2^n subsequences. The DP state is "the best subsequence ending at a[i]a[i]", because whatever comes next only needs to know the last element:

lis[i]=1+max⁡{lis[j]:j<i, a[j]<a[i]},\text{lis}[i] = 1 + \max\{\text{lis}[j] : j < i,\ a[j] < a[i]\},

where the maximum of an empty set is 0. The answer is max⁡ilis[i]\max_i \text{lis}[i], not lis[n−1]\text{lis}[n-1]: the best subsequence may end anywhere. Each ii scans every j<ij < i, so the time is Θ(n2)\Theta(n^2).

Predict before you look

How long is a longest strictly increasing subsequence of [3,1,4,1,5,9,2,6][3, 1, 4, 1, 5, 9, 2, 6]?

Show the answer

4

The table is lis=1,1,2,1,3,4,2,4\text{lis} = 1, 1, 2, 1, 3, 4, 2, 4, with maximum 4, reached for example by 3,4,5,93, 4, 5, 9 and by 1,4,5,61, 4, 5, 6. The second 1 cannot follow the first: strictly increasing means no repeats.

For large nn there is a faster method. Keep, for every length kk, the smallest possible last element ("tail") of an increasing subsequence of length k+1k + 1 seen so far. The tails are sorted, so each new element finds its place by binary search: it either extends the longest subsequence or lowers one tail. The Optimal lesson proves why this works; here is the algorithm, often called patience sorting.

python
from bisect import bisect_left

def lis_length(a):                   # O(n log n)
    tails = []                       # tails[k]: smallest tail of an increasing subsequence of length k + 1
    for x in a:
        k = bisect_left(tails, x)    # strictly increasing: the first tail >= x
        if k == len(tails):
            tails.append(x)          # x extends the longest subsequence so far
        else:
            tails[k] = x             # x is a smaller tail for length k + 1
    return len(tails)

print(lis_length([31, 12, 47, 25, 39, 18, 52, 44, 60, 36]))   # 5

On this input the tails end as [12,18,36,44,60][12, 18, 36, 44, 60]: the right length, but not a subsequence, since 36 comes after 60 in the input. Recovering an actual LIS needs predecessor pointers, which the Optimal lesson adds. For non-decreasing subsequences, use bisect_right.

cpp
#include <algorithm>
#include <cstdio>
#include <vector>

int main() {
    std::vector<int> a = {31, 12, 47, 25, 39, 18, 52, 44, 60, 36};
    std::vector<int> tails;
    for (int x : a) {
        auto it = std::lower_bound(tails.begin(), tails.end(), x);   // upper_bound: non-decreasing
        if (it == tails.end()) tails.push_back(x);
        else *it = x;
    }
    std::printf("%zu\n", tails.size());   // 5
}

The contest idiom: std::lower_bound for strictly increasing, std::upper_bound for non-decreasing. For n=2×105n = 2 \times 10^5 this is about 3.5×1063.5 \times 10^6 comparisons, while the quadratic table would need 2×10102 \times 10^{10} steps.

Two sequences: the LCS table

With two sequences, the state is a pair of prefixes: dp[i][j]\text{dp}[i][j] is the length of a longest common subsequence of a[0..i)a[0..i) and b[0..j)b[0..j):

dp[i][j]={dp[i−1][j−1]+1if a[i−1]=b[j−1],max⁡(dp[i−1][j], dp[i][j−1])otherwise,\text{dp}[i][j] = \begin{cases} \text{dp}[i-1][j-1] + 1 & \text{if } a[i-1] = b[j-1], \\ \max\big(\text{dp}[i-1][j],\ \text{dp}[i][j-1]\big) & \text{otherwise,} \end{cases}

with zeros in row and column 0. That is O(nm)O(nm) time, and O(min⁡(n,m))O(\min(n, m)) space for the length alone (two rows, the shorter string on the columns). A traceback needs the whole table, unless you use Hirschberg's linear-space divide and conquer.

Edit distance

The edit distance (Levenshtein distance) between aa and bb is the fewest insertions, deletions and substitutions of single characters that turn aa into bb. Wagner and Fischer (1974) gave the table: D[i][j]D[i][j] is the distance between a[0..i)a[0..i) and b[0..j)b[0..j).

D[i][j]=min⁡{D[i−1][j−1]+[ a[i−1]≠b[j−1] ]keep or substituteD[i−1][j]+1delete a[i−1]D[i][j−1]+1insert b[j−1]D[i][j] = \min\begin{cases} D[i-1][j-1] + [\,a[i-1] \ne b[j-1]\,] & \text{keep or substitute} \\ D[i-1][j] + 1 & \text{delete } a[i-1] \\ D[i][j-1] + 1 & \text{insert } b[j-1] \end{cases}
with D[i][0]=iD[i][0] = i (delete everything) and D[0][j]=jD[0][j] = j (insert everything); [⋅][\cdot] is 1 if the condition holds and 0 otherwise.
DerivationProof: look at the last column of an alignment
  1. (a[i−1]b[j−1]),(a[i−1]−),(−b[j−1])\begin{pmatrix} a[i-1] \\ b[j-1] \end{pmatrix}, \qquad \begin{pmatrix} a[i-1] \\ - \end{pmatrix}, \qquad \begin{pmatrix} - \\ b[j-1] \end{pmatrix}

    Write an edit script as an alignment: the two strings one above the other, with gaps (−). Each column is a match (cost 0), a substitution (cost 1), a deletion (a letter over a gap) or an insertion (a gap over a letter), and the cost is the number of edits. The last column of an alignment of a[0..i)a[0..i) with b[0..j)b[0..j) has one of three forms:

  2. D[i][j] ≥ min⁡(D[i−1][j−1]+[ a[i−1]≠b[j−1] ], D[i−1][j]+1, D[i][j−1]+1)D[i][j] \ \ge\ \min\big(D[i-1][j-1] + [\,a[i-1] \ne b[j-1]\,],\ D[i-1][j] + 1,\ D[i][j-1] + 1\big)

    Removing it leaves an alignment of (a[0..i−1),b[0..j−1))(a[0..i-1), b[0..j-1)), of (a[0..i−1),b[0..j))(a[0..i-1), b[0..j)) or of (a[0..i),b[0..j−1))(a[0..i), b[0..j-1)), which costs at least the optimum for those prefixes. So an optimal alignment costs at least the minimum of the three cases:

  3. D[i][j]=min⁡(D[i−1][j−1]+[ a[i−1]≠b[j−1] ], D[i−1][j]+1, D[i][j−1]+1)D[i][j] = \min\big(D[i-1][j-1] + [\,a[i-1] \ne b[j-1]\,],\ D[i-1][j] + 1,\ D[i][j-1] + 1\big)

    Conversely, appending the matching column to an optimal alignment of the smaller prefixes gives an alignment with exactly that cost, so the minimum is attained. A column of two gaps is never useful, so the three cases are complete.

python
def edit_distance(a, b):                 # O(nm) time, O(m) space
    prev = list(range(len(b) + 1))       # row 0: D[0][j] = j
    for i, x in enumerate(a, 1):
        cur = [i] + [0] * len(b)         # D[i][0] = i
        for j, y in enumerate(b, 1):
            cur[j] = min(prev[j - 1] + (x != y),   # keep or substitute
                         prev[j] + 1,              # delete x
                         cur[j - 1] + 1)           # insert y
        prev = cur
    return prev[-1]

print(edit_distance('kitten', 'sitting'), edit_distance('recieve', 'receive'))   # 3 2

Two rows suffice for the distance; the script needs the full table or Hirschberg's method.

Weights and scores. Nothing in the proof needs unit costs: with costs for insertion, deletion and each substitution x→yx \to y, the same table finds the cheapest alignment. Biology scores alignments instead, with rewards for matches and penalties for mismatches and gaps, and maximizes: sequence alignment by Needleman and Wunsch (1970) for whole sequences, and by Smith and Waterman (1981) for the best pair of substrings, where every cell may also restart at 0.

Variations on the theme

ProblemChange to the recurrenceAnswer
Longest common substring (contiguous)Match: dp[i−1][j−1]+1\text{dp}[i-1][j-1] + 1; mismatch: 0The maximum over all cells
Shortest common supersequenceThe LCS tablen+m−LCSn + m - \mathrm{LCS}
Fewest deletions to make two strings equalThe LCS tablen+m−2⋅LCSn + m - 2 \cdot \mathrm{LCS}
Longest palindromic subsequenceLCS of ss and its reverse, or intervals L(i,j)L(i, j)LCS(s,sR)\mathrm{LCS}(s, s^R)
Local alignment (Smith–Waterman)Each cell may also take 0The maximum over all cells
Is cc an interleaving of aa and bb?I[i][j]I[i][j]: is c[0..i+j)c[0..i+j) an interleaving of a[0..i)a[0..i) and b[0..j)b[0..j)?I[n][m]I[n][m]
Small changes to the same prefix-pair table. Where the answer is "the maximum over all cells", the best solution may end anywhere, so the corner is not enough.
Check your understanding

What is the longest common substring (contiguous) of ABABC and BABCA, and where in the table is its length?

  1. BABC, length 4: the maximum over the whole table
  2. BABC, length 4: the bottom-right cell
  3. ABC, length 3: the maximum over the whole table
  4. BABCA, length 5: the bottom-right cell
Show the answer

A. BABC, length 4: the maximum over the whole table

With dp[i][j]\text{dp}[i][j] the length of the longest common block ending at a[i−1]a[i-1] and b[j−1]b[j-1] (0 on a mismatch), BABC ends at a[4]a[4] and b[3]b[3], so dp[5][4]=4\text{dp}[5][4] = 4. The bottom-right cell dp[5][5]\text{dp}[5][5] is 0, because C ≠ A: the answer is the maximum anywhere in the table.

Where these tables live. File comparison treats each line as one letter: the original Unix diff used the Hunt–McIlroy LCS algorithm, and Git's default is Myers's algorithm, which explores the edit graph one diagonal at a time. Spell checkers rank corrections by edit distance, DNA and protein aligners use scored alignment, and clone detectors compare token sequences. The Optimal lessons show how these tools go beyond the plain quadratic table.

Recognizing it

Signals of a sequence DP:

  • Two sequences compared position by position: "transform", "align", "common", "interleave", "fewest edits". Use a table over pairs of prefixes, O(nm)O(nm); with n,m≤5000n, m \le 5000 it fits comfortably.
  • "Remove the fewest elements so that the rest is increasing": that is n−LISn - \mathrm{LIS}. Chains of pairs (boxes inside boxes, envelopes) become an LIS after sorting.
  • The size decides the method: n≤5000n \le 5000 allows the O(n2)O(n^2) LIS table; nn up to 2×1052 \times 10^5 needs the O(nlog⁡n)O(n \log n) tails array.
  • "Contiguous" versus "subsequence": substrings and subarrays reset on a mismatch; subsequences carry the best value forward.
Problem (in brief)Key ideaCost
Fewest deletions to make an array strictly increasingn−LISn - \mathrm{LIS}O(nlog⁡n)O(n \log n)
Longest chain of nested envelopesSort by width up, height down for equal widths; LIS of the heightsO(nlog⁡n)O(n \log n)
Edit distance between two wordsWagner–Fischer tableO(nm)O(nm)
Shortest common supersequenceLCS table; the traceback merges the stringsO(nm)O(nm)
Is cc an interleaving of aa and bb?Boolean table over prefix pairsO(nm)O(nm)
Five classics. The envelope trick works because, after the sort, boxes of equal width appear in decreasing height and can never both join a strictly increasing subsequence.
Check your understanding

You have n≤2×105n \le 2 \times 10^5 boxes with distinct widths and distinct heights; a box fits inside another if it is both narrower and lower. How do you find the longest chain of nested boxes in time?

  1. Sort by width, then find an LIS of the heights with the tails array: O(nlog⁡n)O(n \log n)
  2. Sort by width and keep every box taller than the last one kept: O(nlog⁡n)O(n \log n)
  3. An O(n2)O(n^2) DP over all pairs of boxes, which fits easily
  4. The edit distance between the width order and the height order
Show the answer

A. Sort by width, then find an LIS of the heights with the tails array: O(nlog⁡n)O(n \log n)

After sorting by width, a nested chain is exactly an increasing subsequence of the heights, and the tails array finds its length in about nlog⁡2n≈3.5×106n \log_2 n \approx 3.5 \times 10^6 steps. If equal widths were allowed, sorting them by decreasing height would stop two boxes of the same width from both being chosen.

Key takeaways

  • LIS: the state is "best ending at ii", the O(n2)O(n^2) table plus predecessor pointers recovers a subsequence, and the answer is the maximum over ii. The tails array gives the length in O(nlog⁡n)O(n \log n) (bisect_left for strict, bisect_right for non-decreasing), but the array itself is not an LIS.
  • LCS and edit distance use pairs of prefixes: O(nm)O(nm) time, two rows for the value, and a traceback (or Hirschberg) for the solution. Both recurrences follow from the last column of an alignment.
  • Small changes give the variants: 0 on a mismatch for common substrings (answer: the maximum cell), costs for weighted alignment, a restart at 0 for local alignment, and n+m−LCSn + m - \mathrm{LCS} for the shortest common supersequence.
  • Recognize it: two sequences compared position by position mean a prefix-pair table; "fewest removals to make it increasing" and nested pairs mean an LIS; contiguity changes the recurrence; and nn around 10510^5 calls for O(nlog⁡n)O(n \log n) time or linear space.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

For a=[5,6,1,2,3,0]a = [5, 6, 1, 2, 3, 0], what are lis[5]\text{lis}[5] (the best ending at the last element) and the length of an LIS?

  1. lis[5]=3\text{lis}[5] = 3, LIS 3
  2. lis[5]=1\text{lis}[5] = 1, LIS 3
  3. lis[5]=1\text{lis}[5] = 1, LIS 1
  4. lis[5]=2\text{lis}[5] = 2, LIS 2
Show the answer

B. lis[5]=1\text{lis}[5] = 1, LIS 3

The table is 1,2,1,2,3,11, 2, 1, 2, 3, 1. Nothing before 0 is smaller, so lis[5]=1\text{lis}[5] = 1, while 1,2,31, 2, 3 gives the answer 3 at index 4. This is why the answer is the maximum over the whole table.

Question 2

The tails method processes [2,5,3,7,11,8,10,13,6][2, 5, 3, 7, 11, 8, 10, 13, 6]. What is the tails array at the end?

  1. [2,3,7,8,10,13][2, 3, 7, 8, 10, 13], which is also an increasing subsequence
  2. [2,3,6,8,10,13][2, 3, 6, 8, 10, 13], which has the LIS's length but is not a subsequence of the input
  3. [2,5,7,11,13][2, 5, 7, 11, 13]
  4. [2,3,6][2, 3, 6]
Show the answer

B. [2,3,6,8,10,13][2, 3, 6, 8, 10, 13], which has the LIS's length but is not a subsequence of the input

After 13 the tails are [2,3,7,8,10,13][2, 3, 7, 8, 10, 13]; then 6 replaces 7, the first tail ≥6\ge 6. The length 6 is the LIS length (for example 2,3,7,8,10,132, 3, 7, 8, 10, 13), but the array itself puts 6 before 8 although 6 comes last in the input.

Question 3

In the edit-distance table, when a[i−1]=b[j−1]a[i-1] = b[j-1] the value is simply D[i][j]=D[i−1][j−1]D[i][j] = D[i-1][j-1]. Why can the delete and insert options be skipped then?

  1. Because matching letters must always be aligned with each other in every optimal alignment
  2. Because neighboring cells differ by at most 1, so D[i−1][j]+1D[i-1][j] + 1 and D[i][j−1]+1D[i][j-1] + 1 are never below D[i−1][j−1]D[i-1][j-1]
  3. Because insertions and deletions cost more than substitutions
  4. They cannot be skipped; the shortcut is a common bug
Show the answer

B. Because neighboring cells differ by at most 1, so D[i−1][j]+1D[i-1][j] + 1 and D[i][j−1]+1D[i][j-1] + 1 are never below D[i−1][j−1]D[i-1][j-1]

One edit changes the distance by at most one, so D[i−1][j]≥D[i−1][j−1]−1D[i-1][j] \ge D[i-1][j-1] - 1 and D[i][j−1]≥D[i−1][j−1]−1D[i][j-1] \ge D[i-1][j-1] - 1. The other two options therefore cost at least D[i−1][j−1]D[i-1][j-1], and the match wins or ties. Some optimal alignments may still align those letters differently; the shortcut only claims that one optimal alignment keeps the match.

Question 4

Global alignment scores whole sequences. Which change to the table gives Smith–Waterman local alignment, the best-scoring pair of substrings?

  1. Reverse both sequences before filling the table
  2. Let every cell also take the option 0 (start a new alignment here), and report the maximum cell anywhere
  3. Use only the diagonal option
  4. Divide every score by the length of the alignment
Show the answer

B. Let every cell also take the option 0 (start a new alignment here), and report the maximum cell anywhere

The option 0 lets an alignment start anywhere, because a negative-scoring prefix can always be dropped, and taking the best cell anywhere lets it end anywhere. Everything else (the three options, the scoring) stays as in Needleman–Wunsch.

Go deeper

Further reading

  • R. A. Wagner & M. J. Fischer, "The string-to-string correction problem," Journal of the ACM 21(1) (1974), 168–173.
  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), section 14.4.
  • D. Gusfield, Algorithms on Strings, Trees, and Sequences (Cambridge University Press, 1997), part III.
  • S. B. Needleman & C. D. Wunsch, "A general method applicable to the search for similarities in the amino acid sequence of two proteins," Journal of Molecular Biology 48(3) (1970), 443–453.