DP on Sequences and Strings
Solve LIS, LCS, edit distance and palindrome problems by defining states over prefixes or pairs of indices.
Intermediate · about 10 hours · difficulty 4/5
Learn first: 2D DP: Grids and Knapsack, Binary Search
Sequence DP is where interviews get serious. The states are indices into one or two strings or arrays, and many problems are variants of a few classics.
Longest Increasing Subsequence (LIS)
- O(n^2):
dp[i]= length of LIS ending at i, taking the bestdp[j] + 1over j < i witha[j] < a[i]. - O(n log n): maintain
tails[k]= smallest possible tail of an increasing subsequence of length k + 1, updated with binary search. Variants: Russian Doll Envelopes, Number of LIS, longest chain.
Longest Common Subsequence (LCS)
dp[i][j] = LCS of the first i characters of s and the first j of t. If they match, 1 + dp[i-1][j-1]; otherwise max(dp[i-1][j], dp[i][j-1]). Many problems reduce to LCS: minimum insertions/deletions to convert strings, shortest common supersequence, longest palindromic subsequence (LCS of s and reverse(s)).
Edit distance
Same table shape with three operations (insert, delete, replace). Knowing how to reconstruct the actual operations from the table is a strong signal.
Other patterns
- Distinct Subsequences (counting).
- Wildcard and regular expression matching.
- Palindromic substrings with
dp[i][j]over intervals. - Stock problems with states like "holding / not holding / cooldown".
Tip: use 1-indexed tables with an extra row and column for empty prefixes to simplify base cases.
Key concepts
- LIS O(n^2) and O(n log n)
- LCS and its reductions
- Edit distance
- Longest palindromic subsequence
- Distinct subsequences (counting)
- Wildcard and regex matching
- State machine DP (stocks)
- Reconstructing the solution
Mini project
Solve 10 problems: Longest Increasing Subsequence, Russian Doll Envelopes, Longest Common Subsequence, Edit Distance, Delete Operation for Two Strings, Longest Palindromic Subsequence, Distinct Subsequences, Wildcard Matching, Best Time to Buy and Sell Stock with Cooldown, and Interleaving String.
Check yourself
In the O(n log n) LIS algorithm, the tails array is not itself a valid subsequence. Why is its length still the correct answer?
Free resources
- Longest increasing subsequence (cp-algorithms)
- MIT 6.006 (Dynamic Programming lectures) (MIT OCW)
- Dynamic programming (GeeksforGeeks)