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
Example 1
Output: 4
Explanation: one longest palindromic subsequence is "bbbb".
Example 2
Output: 2
Explanation: one longest palindromic subsequence is "bb".
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.
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 dpdp[i][j]sdp[1][3]dp[0][4]
The two cases from "bbbab" and "cbbd" become two rules. When s[i]s[j]dp[i][j] = dp[i + 1][j - 1] + 2dp[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
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]int
The order of filling
In what order can the entries be filled? Each entry reads the row below it, at i + 1j - 1
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 smain
Java Solution
The table is built by a helper method, buildTabledplongestPalindromeSubseq
- First,
setsbuildTable to the length ofn and creates the table withs , full of 0s.new int[n][n] - A loop moves
fromi down to 0, so the rows are filled from the bottom up. Each row starts withn - 1 , the one-letter piece.dp[i][i] = 1 - Inside, a second loop moves
fromj to the end of the string. Ifi + 1 equalss.charAt(i) , the entry becomess.charAt(j) . Otherwise it becomes the larger ofdp[i + 1][j - 1] + 2 anddp[i + 1][j] .dp[i][j - 1] - When both loops are done,
returnslongestPalindromeSubseq , the entry for the whole string.dp[0][n - 1]
The main
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:
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 iii + 1
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
for every start and end, n × n in all, while the two-row version needs only O(n).int
The same length also comes out as the longest common subsequence of ss