SDE & MLE Prep

516. Longest Palindromic Subsequence

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]