sagelearnai

Longest Palindromic Subsequence

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #516

Return the length of the longest palindromic subsequence of s. A subsequence keeps the original order but may skip characters.

Examples

text
"bbbab"  →  4    ("bbbb")
"cbbd"   →  2    ("bb")

Hints

  1. Look at the two ends. If they match, both can be part of the palindrome. If not, at least one of them isn't used.
  2. Equivalently: the LPS of s is the LCS of s and reverse(s).

Approach

Interval DP: dp[i][j] = the LPS length within s[i..j].

text
dp[i][i] = 1
s[i] == s[j]:  dp[i][j] = dp[i+1][j-1] + 2
else:          dp[i][j] = max(dp[i+1][j], dp[i][j-1])

Fill i from n−1 down to 0 and j from i+1 up, so that i+1 (the row below) is ready. A 1-D rolling array is enough: keep the old dp[j−1] of the row below in a temp variable. O(n²) time, O(n) space.

Subsequence vs substring: substring problems (Longest Palindromic Substring) use expand-around-center. Subsequence problems need this DP.

Complexity

Time: O(n²). Space: O(n) rolling (O(n²) as a table).

Python solution
def longestPalindromeSubseq(s):
    n = len(s)
    dp = [0] * n
    for i in range(n - 1, -1, -1):
        dp[i] = 1
        prev = 0                      # dp[i+1][j-1] from the previous row
        for j in range(i + 1, n):
            tmp = dp[j]               # dp[i+1][j]
            if s[i] == s[j]:
                dp[j] = prev + 2
            else:
                dp[j] = max(dp[j], dp[j - 1])
            prev = tmp
    return dp[n - 1]
JavaScript solution
function longestPalindromeSubseq(s) {
  const n = s.length, dp = Array.from({ length: n }, () => new Array(n).fill(0));
  for (let i = n - 1; i >= 0; i--) {
    dp[i][i] = 1;
    for (let j = i + 1; j < n; j++)
      dp[i][j] = s[i] === s[j] ? dp[i + 1][j - 1] + 2 : Math.max(dp[i + 1][j], dp[i][j - 1]);
  }
  return dp[0][n - 1];
}