Dynamic Programming Part 2

In Part 2, we explore dynamic programming in sequences and one-dimensional arrays. These patterns handle problems like comparing sequences, finding increasing sequences, or optimizing subarray computations. The techniques often involve building DP tables (for sequence alignment problems) or single-array DP for linear scans.

This pattern deals with finding commonalities between sequences (often strings) and forms the basis for many string DP problems. The classic LCS problem finds the length of the longest subsequence present in both sequences. Its DP solution uses a 2D table where cell [i][j] represents the LCS length for prefixes of lengths i and j. Many variations build on LCS, such as finding substrings, supersequences, or minimum edits based on the LCS length.

Example Problems:

Longest Common SubsequenceLongest Common SubstringShortest Common SupersequenceMinimum Insertions/Deletions to TransformLongest Palindromic SubsequenceLongest Repeating SubsequenceSequence Pattern Matching

Solution Spotlight: Longest Common Subsequence

This solution computes the length of the Longest Common Subsequence (LCS) for two strings using a DP table. Each entry dp[i][j] is filled by comparing the i-th prefix of the first string and the j-th prefix of the second string. If the current characters match, 1 is added to the result from the previous shorter prefixes (dp[i-1][j-1]). If they do not match, the solution is the max of skipping one character from either string (dp[i-1][j] or dp[i][j-1]). The final answer dp[m][n] gives the LCS length. Variants like Longest Common Substring modify the transition to require consecutive matches, and others like Shortest Common Supersequence or edit distance problems use the LCS length to derive results.

LongestCommonSubsequence.java

Loading code syntax...