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 DP and predecessor pointers, and its length in 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 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 is one whose elements strictly increase. Brute force checks all subsequences. The DP state is "the best subsequence ending at ", because whatever comes next only needs to know the last element:
where the maximum of an empty set is 0. The answer is , not : the best subsequence may end anywhere. Each scans every , so the time is .
How long is a longest strictly increasing subsequence of ?
Show the answer
4
The table is , with maximum 4, reached for example by and by . The second 1 cannot follow the first: strictly increasing means no repeats.
For large there is a faster method. Keep, for every length , the smallest possible last element ("tail") of an increasing subsequence of length 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.
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])) # 5On this input the tails end as : 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.
#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 this is about comparisons, while the quadratic table would need steps.
Two sequences: the LCS table
With two sequences, the state is a pair of prefixes: is the length of a longest common subsequence of and :
with zeros in row and column 0. That is time, and 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 and is the fewest insertions, deletions and substitutions of single characters that turn into . Wagner and Fischer (1974) gave the table: is the distance between and .
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 with has one of three forms:
Removing it leaves an alignment of , of or of , which costs at least the optimum for those prefixes. So an optimal alignment costs at least the minimum of the three cases:
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.
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 2Two 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 , 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
| Problem | Change to the recurrence | Answer |
|---|---|---|
| Longest common substring (contiguous) | Match: ; mismatch: 0 | The maximum over all cells |
| Shortest common supersequence | The LCS table | |
| Fewest deletions to make two strings equal | The LCS table | |
| Longest palindromic subsequence | LCS of and its reverse, or intervals | |
| Local alignment (Smith–Waterman) | Each cell may also take 0 | The maximum over all cells |
| Is an interleaving of and ? | : is an interleaving of and ? |
What is the longest common substring (contiguous) of ABABC and BABCA, and where in the table is its length?
- BABC, length 4: the maximum over the whole table
- BABC, length 4: the bottom-right cell
- ABC, length 3: the maximum over the whole table
- BABCA, length 5: the bottom-right cell
Show the answer
A. BABC, length 4: the maximum over the whole table
With the length of the longest common block ending at and (0 on a mismatch), BABC ends at and , so . The bottom-right cell 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, ; with it fits comfortably.
- "Remove the fewest elements so that the rest is increasing": that is . Chains of pairs (boxes inside boxes, envelopes) become an LIS after sorting.
- The size decides the method: allows the LIS table; up to needs the tails array.
- "Contiguous" versus "subsequence": substrings and subarrays reset on a mismatch; subsequences carry the best value forward.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Fewest deletions to make an array strictly increasing | ||
| Longest chain of nested envelopes | Sort by width up, height down for equal widths; LIS of the heights | |
| Edit distance between two words | Wagner–Fischer table | |
| Shortest common supersequence | LCS table; the traceback merges the strings | |
| Is an interleaving of and ? | Boolean table over prefix pairs |
You have 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?
- Sort by width, then find an LIS of the heights with the tails array:
- Sort by width and keep every box taller than the last one kept:
- An DP over all pairs of boxes, which fits easily
- 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:
After sorting by width, a nested chain is exactly an increasing subsequence of the heights, and the tails array finds its length in about 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 ", the table plus predecessor pointers recovers a subsequence, and the answer is the maximum over . The tails array gives the length in (
bisect_leftfor strict,bisect_rightfor non-decreasing), but the array itself is not an LIS. - LCS and edit distance use pairs of prefixes: 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 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 around calls for time or linear space.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
For , what are (the best ending at the last element) and the length of an LIS?
- , LIS 3
- , LIS 3
- , LIS 1
- , LIS 2
Show the answer
B. , LIS 3
The table is . Nothing before 0 is smaller, so , while gives the answer 3 at index 4. This is why the answer is the maximum over the whole table.
The tails method processes . What is the tails array at the end?
- , which is also an increasing subsequence
- , which has the LIS's length but is not a subsequence of the input
Show the answer
B. , which has the LIS's length but is not a subsequence of the input
After 13 the tails are ; then 6 replaces 7, the first tail . The length 6 is the LIS length (for example ), but the array itself puts 6 before 8 although 6 comes last in the input.
In the edit-distance table, when the value is simply . Why can the delete and insert options be skipped then?
- Because matching letters must always be aligned with each other in every optimal alignment
- Because neighboring cells differ by at most 1, so and are never below
- Because insertions and deletions cost more than substitutions
- They cannot be skipped; the shortcut is a common bug
Show the answer
B. Because neighboring cells differ by at most 1, so and are never below
One edit changes the distance by at most one, so and . The other two options therefore cost at least , 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.
Global alignment scores whole sequences. Which change to the table gives Smith–Waterman local alignment, the best-scoring pair of substrings?
- Reverse both sequences before filling the table
- Let every cell also take the option 0 (start a new alignment here), and report the maximum cell anywhere
- Use only the diagonal option
- 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
- Longest Increasing Subsequence in O(n log n) · Patience sorting, binary search and the Erdős–Szekeres theorem.
- Edit Distance & Its Limits · Alignment, bit-parallel speedups and the SETH lower bound.
- Longest Common Subsequence in Depth · Hunt–Szymanski, bit-parallel LCS, and why many strings make it NP-hard.
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.