516. Longest Palindromic Subsequence
Asked at 13Microsoft40Amazon40Google31Meta26Bloomberg25MathWorks56Goldman Sachs54MAQ Software69Nutanix60LinkedIn57Uber50Infosys45tcs42
Problem
Return the length of the longest subsequence of s that is a palindrome.
Example: "bbbab" → 4 ("bbbb"); "cbbd" → 2
Constraints: length ≤ 1000.
Interval DP: dp[l][r] = dp[l+1][r−1] + 2 if ends match, else max(dp[l+1][r], dp[l][r−1]). (Equivalently LCS of s and reverse(s).)
Complexity: O(n²).
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
dp = [0] * n # dp[r] for current l
for l in range(n - 1, -1, -1):
dp[l], diag = 1, 0 # diag = old dp[l+1][r-1]
for r in range(l + 1, n):
tmp = dp[r]
dp[r] = diag + 2 if s[l] == s[r] else max(dp[r], dp[r - 1])
diag = tmp
return dp[n - 1]
assert Solution().longestPalindromeSubseq("bbbab") == 4
assert Solution().longestPalindromeSubseq("cbbd") == 2
class Solution {
public int longestPalindromeSubseq(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for (int l = n - 1; l >= 0; l--) {
dp[l][l] = 1;
for (int r = l + 1; r < n; r++)
dp[l][r] = s.charAt(l) == s.charAt(r) ? dp[l + 1][r - 1] + 2 : Math.max(dp[l + 1][r], dp[l][r - 1]);
}
return dp[0][n - 1];
}
}
func longestPalindromeSubseq(s string) int {
n := len(s)
dp := make([]int, n) // dp[r] = answer for s[l..r] with the current l
for l := n - 1; l >= 0; l-- {
dp[l] = 1
diag := 0 // old dp[l+1][r-1]
for r := l + 1; r < n; r++ {
tmp := dp[r]
if s[l] == s[r] {
dp[r] = diag + 2
} else {
dp[r] = max(dp[r], dp[r-1])
}
diag = tmp
}
}
return dp[n-1]
}