Command Palette

Search for a command to run...

Module 31

DP on Strings and Sequences

Subsequences and alignments: LIS in O(n log n), LCS and edit distance tables, palindromic DP, counting subsequences, interleaving and wildcard matching.

Advanced 3 lessons 9 problems ~45 min of lessons

String and sequence DP compares prefixes. For one sequence, the state is usually "best answer ending at index i" (longest increasing subsequence). For two sequences, it's a table indexed by "first i characters of one, first j of the other", and each cell looks at its left, upper and diagonal neighbours.

This module covers the longest increasing subsequence (including the patience-sorting speed-up), longest common subsequence, edit distance, palindromic subsequences and substrings, counting distinct subsequences, interleaving strings, and pattern matching with wildcards.

Best after: DP on Grids

Part 1

Learn the ideas

Part 2

Solve the problems

In order of difficulty. Each one shows the pattern it teaches.

  1. The quadratic DP, then the tails array with binary search.

  2. Turn a 2D chain into 1D LIS by sorting width ascending and height descending.

  3. The two-sequence table: diagonal on a match, best neighbour otherwise.

  4. Three operations, three neighbours: replace (diagonal), delete (up), insert (left).

  5. Interval DP on one string: peel matching ends.

  6. Counting palindromes: expand from 2n − 1 centres, or a boolean interval table.

  7. Counting alignments: on a match, either use the character or skip it.

  8. A boolean grid over two strings; the third string's position is implied by i + j.

  9. A star matches empty (move in the pattern) or one more character (move in the string).