DP on Subsequences and Strings: LIS, LCS, Edit Distance

Solve the classic sequence DPs: longest increasing subsequence, longest common subsequence and its variants, edit distance and wildcard matching.

Advanced · about 9 hours · difficulty 4/5

Learn first: Knapsack and Subset DP, Binary Search on Arrays

Sequence DPs compare positions in one or two arrays or strings. They are the most asked DP problems in product-company interviews.

Longest Increasing Subsequence

  • O(n^2) DP: dp[i] = 1 + max dp[j] for j < i with a[j] < a[i].
  • O(n log n): keep tails[] where tails[k] is the smallest tail of an increasing subsequence of length k + 1; binary search each element into it.
  • Variants: Number of LIS, Largest Divisible Subset, Russian Doll Envelopes (sort cleverly, then LIS), Longest String Chain, Longest Bitonic Subsequence.

Two-string DP, state (i, j)

  • Longest Common Subsequence: match then 1 + dp[i - 1][j - 1], else max of skipping one side.
  • From LCS: Longest Palindromic Subsequence (LCS with the reverse), minimum insertions to make a palindrome, Shortest Common Supersequence, Delete Operation for Two Strings.
  • Longest Common Substring: reset to 0 on mismatch.
  • Edit Distance: insert, delete, replace.
  • Distinct Subsequences, Wildcard Matching, Regular Expression Matching.

Pitfalls

  • Confusing subsequence (gaps allowed) with substring (contiguous).
  • Index shifting: using 1-based dp with 0-based strings and reading s[i] instead of s[i - 1].
  • Printing the actual LCS needs a backtrack through the table, a common follow-up.

You are ready to move on when you can solve Edit Distance and LIS in O(n log n) and print the actual LCS string, not just its length.

Key concepts

  • LIS in O(n^2)
  • LIS in O(n log n)
  • LCS and printing it
  • Longest palindromic subsequence
  • Edit distance
  • Distinct subsequences
  • Wildcard and regex matching
  • Subsequence vs substring

Mini project

Solve these 10 in 7 days, log time and pattern: Longest Increasing Subsequence (both methods), Number of Longest Increasing Subsequence, Largest Divisible Subset, Russian Doll Envelopes, Longest Common Subsequence (print it too), Longest Palindromic Subsequence, Shortest Common Supersequence, Edit Distance, Distinct Subsequences, Wildcard Matching.

Check yourself

In the O(n log n) LIS method, is the tails array itself a valid increasing subsequence? Why or why not?

Free resources