Dynamic Programming · Pattern 8 of 12

String DP: two indexes, one per string

dp[i][j] describes the first i characters of one string and the first j of the other (or the substring s[i..j]). If the last characters match, move both; if not, try each way of dropping one.

5 variations · 16 problems · 6 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Compare two strings: common subsequence, edits, interleaving
  • Palindromic subsequences or substrings
  • Match a string against a pattern with ., * or ?

The template

Strings
// LCS: dp[i][j] = longest common subsequence of a[0..i) and b[0..j)
int longestCommonSubsequence(String a, String b) {
    int n = a.length(), m = b.length();
    int[][] dp = new int[n + 1][m + 1];    // row 0 and column 0: an empty string, LCS 0
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
                ? dp[i - 1][j - 1] + 1
                : Math.max(dp[i - 1][j], dp[i][j - 1]);
    return dp[n][m];
}

// Edit Distance: dp[i][j] = edits to turn a[0..i) into b[0..j)
int minDistance(String a, String b) {
    int n = a.length(), m = b.length();
    int[][] dp = new int[n + 1][m + 1];
    for (int i = 0; i <= n; i++) dp[i][0] = i;   // delete everything
    for (int j = 0; j <= m; j++) dp[0][j] = j;   // insert everything
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
                ? dp[i - 1][j - 1]
                : 1 + Math.min(dp[i - 1][j - 1], Math.min(dp[i - 1][j], dp[i][j - 1])); // replace, delete, insert
    return dp[n][m];
}

// Longest Palindromic Subsequence: dp[i][j] = answer for s[i..j]
int longestPalindromeSubseq(String s) {
    int n = s.length();
    int[][] dp = new int[n][n];
    for (int i = n - 1; i >= 0; i--) {     // i goes down, so row i + 1 is ready
        dp[i][i] = 1;
        for (int j = i + 1; j < n; j++)
            dp[i][j] = s.charAt(i) == s.charAt(j)
                ? dp[i + 1][j - 1] + 2
                : Math.max(dp[i + 1][j], dp[i][j - 1]);
    }
    return dp[0][n - 1];
}

The variations

  1. 1Two strings, a prefix of each

    If the last characters match, use dp[i - 1][j - 1]. Otherwise drop a character from one string or the other (LCS), or pay for an edit (Edit Distance). Counting versions add instead: Distinct Subsequences, Interleaving String and Ways to Form a Target all have this shape.

  2. 2Contiguous match: common substring

    dp[i][j] = length of the common run ending at a[i - 1] and b[j - 1]. A match extends the diagonal by 1; a mismatch resets to 0. The answer is the biggest cell, not the last one.

  3. 3Palindromes inside one string

    dp[i][j] works on s[i..j]. Equal ends add 2 to the inside; otherwise drop one end. Minimum insertions = n minus the longest palindromic subsequence. For substrings, isPal[i][j] = s[i] == s[j] && isPal[i + 1][j - 1], which also feeds Palindrome Partitioning II.

  4. 4Pattern matching with wildcards

    dp[i][j] = does s[0..i) match p[0..j). A * either matches nothing (use dp[i][j - 2] for regex, dp[i][j - 1] for wildcard) or eats one more character of s (use dp[i - 1][j]).

    Now you solve
  5. 5One string, answer ending at i

    Longest Valid Parentheses: dp[i] = the longest valid run ending at i, built from the run just before its matching (. Ways to Separate Numbers uses dp[i][len] with the last number's length as part of the state.

Mistakes to avoid

  • Mixing up subsequence and substring: for a substring, a mismatch resets dp[i][j] to 0 and the answer is the max over all cells.
  • Forgetting the empty-string row and column: Edit Distance needs dp[i][0] = i and dp[0][j] = j.
  • Filling a palindrome table dp[i][j] with i going up: it reads dp[i + 1][...], so i must go down (or fill by length).
Next: Interval DP: solve every range, short to long →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.