Longest Palindromic Subsequence

Find how many letters of a string can be kept, in order, so that they read the same both ways.

Given a string s, return the length of its longest palindromic subsequence. A subsequence is what is left after deleting any number of characters, with the others kept in their order. It is palindromic when it reads the same from the left and from the right, like "bbbb" in Example 1.

Example 1
Input: s = "bbbab"
Output: 4
Explanation: one longest palindromic subsequence is "bbbb".
Example 2
Input: s = "cbbd"
Output: 2
Explanation: one longest palindromic subsequence is "bb".
Solution

The Idea

Write "bbbab" on a strip of paper and cross out some letters without moving the others. Cross out the a, and the letters left, "bbbb", read the same from either end. Cross out nothing, and "bbbab" reads "babbb" backwards, so it does not count. No leftover longer than 4 letters works, so the answer is 4.

For "cbbd" the best leftover is "bb", 2 letters. How do we find the longest one without trying every way of crossing out letters? Each of the 5 letters of "bbbab" is either kept or crossed out, which makes 25 = 32 choices, and each extra letter doubles that number.

Look at the two ends of "bbbab" instead. The first and last letters are both b. A palindrome starts and ends with the same letter, so these two b's can be its outer pair. Between them sits "bba", and the best palindrome inside "bba" is "bb", 2 letters. Wrapping it in the two outer b's gives "bbbb", 2 + 2 = 4.

The ends of "cbbd" are c and d. They differ, so they cannot be the outer pair of one palindrome, and at least one of them is left out. The answer is then the better of "bbd", without the c, and "cbb", without the d. Both give 2.

Either way, the question for the whole string becomes the same question for a shorter piece of it. A piece is fixed by its start position i and its end position j, so the answers fit in a table. Row i, column j holds the length of the longest palindromic subsequence of the piece from i to j. Look at the picture below.

The string bbbab with the outer b at positions 0 and 4 marked and the inside bba under a bracket. Next to it, the filled table for bbbab with start i as rows and end j as columns. Row 1, column 3 holds 2 for bba, and an arrow leads to row 0, column 4, which holds 2 + 2 = 4.

On the left, the b's at positions 0 and 4 are the matching ends, and the bracket marks the inside, "bba". On the right, the row labelled 1 (b) and the column labelled 3 (a) meet at the teal 2, the answer for "bba". The arrow leads to the orange 4 in row 0, column 4, the answer for the whole string.

Each entry is worked out once from entries for shorter pieces, and those are read from the table rather than worked out again. Building the answer for "bbbab" from stored answers to "bba", "bb" and the other pieces this way is called dynamic programming.

Solution Approach

Turning the table into code means settling three things: what each entry holds, which entries are known from the start, and in what order to fill the rest. An optional change then keeps only two rows.

What one entry holds

What exactly is stored in the table, called dp in the code? The entry dp[i][j] is the length of the longest palindromic subsequence of s from position i to position j, both included. For "bbbab", dp[1][3] is the answer for "bba", which is 2, and dp[0][4] is the answer for the whole string.

The two cases from "bbbab" and "cbbd" become two rules. When s[i] equals s[j], the ends wrap the best palindrome of the inside: dp[i][j] = dp[i + 1][j - 1] + 2. When they differ, one end is dropped, whichever leaves more: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]).

Why store the entries at all? A method that applies the rules to the whole string, then to the shorter pieces, and so on, meets the same piece many times. For example, "bbba" and "bbab" both shrink to "bba" by dropping one end. With the table, "bba" is worked out once and read after that.

Entries known from the start

Which entries need no rule? A piece of one letter, such as the a at position 3, is a palindrome by itself, so dp[i][i] = 1 for every i. These are the 1s on the diagonal of the picture.

A piece of two equal letters, such as "bb" from position 0 to 1, follows the matching-ends rule with an empty inside. That inside is dp[1][0], a grey cell where the end comes before the start. Java fills a new int array with 0s, so the grey cells stay 0, and the result is 0 + 2 = 2.

The order of filling

In what order can the entries be filled? Each entry reads the row below it, at i + 1, and the column to its left, at j - 1. So the rows go from the bottom, row 4, up to row 0, and each row goes from left to right. In the picture, the teal 2 in row 1 is filled before the orange 4 in row 0 reads it.

Optional: keeping two rows

Does the whole table need to stay in memory? Each row reads only itself and the row below, so two arrays of length n, where n is the length of s, are enough. That brings the memory from n × n numbers down to 2n. The code below keeps the full table so that main can print it and compare it with the picture.

Java Solution

The table is built by a helper method, buildTable, which fills dp and returns it. The method longestPalindromeSubseq calls it and reads one entry. Together they work in these steps:

  1. First, buildTable sets n to the length of s and creates the table with new int[n][n], full of 0s.
  2. A loop moves i from n - 1 down to 0, so the rows are filled from the bottom up. Each row starts with dp[i][i] = 1, the one-letter piece.
  3. Inside, a second loop moves j from i + 1 to the end of the string. If s.charAt(i) equals s.charAt(j), the entry becomes dp[i + 1][j - 1] + 2. Otherwise it becomes the larger of dp[i + 1][j] and dp[i][j - 1].
  4. When both loops are done, longestPalindromeSubseq returns dp[0][n - 1], the entry for the whole string.

The main method runs both examples, a single letter, "abcd" with no letter repeated, and "agbdba", then prints the table for "bbbab" row by row.

Java
import java.util.Arrays;

public class LongestPalindromeSubsequence {

    // dp[i][j] is the length of the longest palindromic subsequence of s[i..j]
    static int[][] buildTable(String s) {
        int n = s.length();
        int[][] dp = new int[n][n];
        for (int i = n - 1; i >= 0; i--) {             // start rows from the bottom
            dp[i][i] = 1;                              // one character on its own
            for (int j = i + 1; j < n; j++) {
                if (s.charAt(i) == s.charAt(j)) {
                    dp[i][j] = dp[i + 1][j - 1] + 2;   // both ends wrap the inside
                } else {
                    dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);   // drop one end
                }
            }
        }
        return dp;
    }

    public static int longestPalindromeSubseq(String s) {
        return buildTable(s)[0][s.length() - 1];
    }

    public static void main(String[] args) {
        System.out.println(longestPalindromeSubseq("bbbab"));
        System.out.println(longestPalindromeSubseq("cbbd"));
        System.out.println(longestPalindromeSubseq("a"));
        System.out.println(longestPalindromeSubseq("abcd"));
        System.out.println(longestPalindromeSubseq("agbdba"));

        System.out.println("Table for bbbab, row i = start, column j = end:");
        for (int[] row : buildTable("bbbab")) {
            System.out.println(Arrays.toString(row));
        }
    }
}

Running it prints:

Output
4
2
1
1
5
Table for bbbab, row i = start, column j = end:
[1, 2, 3, 3, 4]
[0, 1, 2, 2, 3]
[0, 0, 1, 1, 3]
[0, 0, 0, 1, 1]
[0, 0, 0, 0, 1]

The 4 and the 2 at the top match the two examples. The single "a" gives 1, and so does "abcd": with four different letters, any one letter on its own is the longest palindrome. The 5 comes from "agbdba", where crossing out the g leaves "abdba".

The printed table is the one in the picture. Row 0 ends in 4, the answer for "bbbab", and row 1 holds the 2 for "bba" in its fourth place, column 3. The 0s below the diagonal are the grey cells.

The direction of the loop over i matters. A version that moves i up from 0 reads row i + 1 while it is still all 0s. Run on the examples, that version prints 2 for "bbbab" and 1 for "cbbd", instead of 4 and 2.

Complexity

The work is one pass over the upper half of the table, with a fixed amount of work per entry.

  • Time: O(n²), because the two loops visit each pair of a start i and a later end j once, about n²/2 entries for a string of n letters, each with one comparison and one addition or Math.max.
  • Space: O(n²), because the table keeps one int for every start and end, n × n in all, while the two-row version needs only O(n).

The same length also comes out as the longest common subsequence of s and s written backwards: see Longest Common Subsequence.