Longest Palindromic Subsequence
Medium
Topics
A subsequence is what remains after deleting any number of characters without reordering the rest, so it need not be contiguous.
Return the length of the longest subsequence of s that is a palindrome.
Example 1
bbbb, which reads the same backwards, and its length 4 is the answer. The gaps are the point: a longest contiguous run that reads the same both ways would be shorter than this.Input: s = "bbbab" Output: 4 Explanation: Deleting the a leaves "bbbb". The longest contiguous palindrome is only "bbb", which is why subsequences matter here.
Example 2
Input: s = "cbbd" Output: 2 Explanation: "bb" — nothing of length 3 mirrors itself.
Example 3
Input: s = "a" Output: 1 Explanation: A single character is a palindrome.
Constraints
- 1 <= s.length <= 1000
- s consists of lowercase English letters
Editorial — intuition, approach, complexity and pitfalls
Intuition
Look at the two ends of a stretch of the string. If they match, both can be kept: they wrap whatever the best palindrome inside them is, adding two to its length. If they do not match, at least one of them has to go, and which one is not obvious — so both possibilities are tried and the better kept.
That recursion is over ranges, not positions, which is the structural point: a palindrome is defined by a pair of ends closing in on each other, so the state is an interval. The same interval is reached by many different deletion orders, which is what makes remembering results worthwhile.
A single character is a palindrome of length 1 and an empty range has length 0, and those two base cases are all the recursion needs.
Worth knowing the shortcut: this is the longest common subsequence of s and its reverse. Same answer, and it reuses a routine you may already have.
Approach
- Define the answer for a range as the length of the longest palindromic subsequence within it.
- A range of one character is 1; an empty range is 0.
- If the two end characters match, the answer is two plus the answer for the range strictly inside them.
- If they do not, it is the better of dropping the left end or dropping the right end.
- Fill the ranges from shortest to longest so each one reads results that are already known, and read off the answer for the whole string.
Walkthrough
s = "bbbab"
01234
ranges by length (value = longest palindromic subsequence)
length 1 b b b a b all 1
length 2 bb=2 bb=2 ba=1 ab=1
length 3 bbb=3 bba=2 bab=3
length 4 bbba=3 bbab=4
length 5 bbbab=4
the last one: ends are b and b, they match, so it is
2 + answer("bba" inside) = 2 + 2 = 4
answer 4
"bbbb" is the subsequence -- the a in the middle is deleted,
which a contiguous reading could not do.Complexity
- Time — O(n^2): one entry per range, each computed from a constant number of shorter ranges.
- Space — O(n^2): the table. Only two rows are needed at a time, which brings it to O(n).
Common Pitfalls
- Solving for the longest palindromic substring instead. Example 1 answers 4 as a subsequence and 3 as a substring.
- Adding 2 for a matching pair when the range has only two characters, and then reading an inside range that does not exist. The inner range is empty there and contributes 0.
- Filling the table in row order rather than by increasing range length. A range then reads a longer range that has not been computed.
- Assuming the matching-ends case never needs the mismatching branch. When the ends match, keeping both is always at least as good — that part is safe — but the reverse is not true, so the mismatching case must try both drops.
Full Solution — all languages
class Solution:
def longestPalindromeSubseq(self, s):
n = len(s)
if n == 0:
return 0
best = [[0] * n for _ in range(n)]
for i in range(n):
best[i][i] = 1
for length in range(2, n + 1):
for i in range(n - length + 1):
j = i + length - 1
if s[i] == s[j]:
best[i][j] = 2 + (best[i + 1][j - 1] if length > 2 else 0)
else:
best[i][j] = max(best[i + 1][j], best[i][j - 1])
return best[0][n - 1]import java.util.*;
class Solution {
public int longestPalindromeSubseq(String s) {
int n = s.length();
if (n == 0) return 0;
int[][] best = new int[n][n];
for (int i = 0; i < n; i++) best[i][i] = 1;
for (int length = 2; length <= n; length++) {
for (int i = 0; i + length - 1 < n; i++) {
int j = i + length - 1;
if (s.charAt(i) == s.charAt(j)) {
best[i][j] = 2 + (length > 2 ? best[i + 1][j - 1] : 0);
} else {
best[i][j] = Math.max(best[i + 1][j], best[i][j - 1]);
}
}
}
return best[0][n - 1];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int longestPalindromeSubseq(string s) {
int n = (int)s.size();
if (n == 0) return 0;
vector<vector<int>> best(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) best[i][i] = 1;
for (int length = 2; length <= n; length++) {
for (int i = 0; i + length - 1 < n; i++) {
int j = i + length - 1;
if (s[i] == s[j]) best[i][j] = 2 + (length > 2 ? best[i + 1][j - 1] : 0);
else best[i][j] = max(best[i + 1][j], best[i][j - 1]);
}
}
return best[0][n - 1];
}
};/**
* @param {string} s
* @return {number}
*/ var longestPalindromeSubseq = function(s) {
const n = s.length;
if (!n) return 0;
const best = Array.from({ length: n }, () => new Array(n).fill(0));
for (let i = 0; i < n; i++) best[i][i] = 1;
for (let length = 2; length <= n; length++) {
for (let i = 0; i + length - 1 < n; i++) {
const j = i + length - 1;
if (s[i] === s[j]) best[i][j] = 2 + (length > 2 ? best[i + 1][j - 1] : 0);
else best[i][j] = Math.max(best[i + 1][j], best[i][j - 1]);
}
}
return best[0][n - 1];
};