Longest Palindromic Subsequence

Pattern: Strings DP

medium

dp[i][j] is the longest palindromic subsequence inside s[i..j]. Equal ends wrap the inside (2 + dp[i+1][j-1]); otherwise drop one end. It also equals the LCS of s and its reverse.

The problem

Return the length of the longest subsequence of s that reads the same backwards.

Think first

  • What if the first and last characters match?
  • And if they do not?
  • In what order are segments filled?

Hints

    Brute force, and why it fails

    Try every subsequence: 2ⁿ.

    The key insight

    A palindrome's outer pair and its inside are independent, so segments of s are the states.

    Dry run

    'bbbab'. Single characters: 1. 'bb': 2.

    Step 1 of 2

    The plan

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

    Complexity

    Time
    O(n²)
    Space
    O(n²)

    Every segment once (O(n) memory is possible).

    Edge cases

    • One character: 1.
    • All different: 1.
    • Already a palindrome: n.
    I've built my logic, show the code

    Java

    class Solution {
        public int longestPalindromeSubseq(String s) {
            int n = s.length();
            int[][] dp = new int[n][n];             // dp[i][j]: the longest palindrome inside s[i..j]
            for (int i = n - 1; i >= 0; i--) {
                dp[i][i] = 1;
                for (int j = i + 1; j < n; j++)
                    dp[i][j] = s.charAt(i) == s.charAt(j)
                        ? dp[i + 1][j - 1] + 2                       // matching ends wrap the inside
                        : Math.max(dp[i + 1][j], dp[i][j - 1]);      // drop one end
            }
            return dp[0][n - 1];
        }
    }

    C++

    class Solution {
    public:
        int longestPalindromeSubseq(string s) {
            int n = static_cast<int>(s.size());
            vector<vector<int>> dp(n, vector<int>(n, 0));   // dp[i][j]: the longest palindrome inside s[i..j]
            for (int i = n - 1; i >= 0; i--) {
                dp[i][i] = 1;
                for (int j = i + 1; j < n; j++)
                    dp[i][j] = s[i] == s[j]
                        ? dp[i + 1][j - 1] + 2                       // matching ends wrap the inside
                        : max(dp[i + 1][j], dp[i][j - 1]);           // drop one end
            }
            return dp[0][n - 1];
        }
    };

    Python

    class Solution:
        def longestPalindromeSubseq(self, s: str) -> int:
            n = len(s)
            dp = [[0] * n for _ in range(n)]        # dp[i][j]: the longest palindrome inside s[i..j]
            for i in range(n - 1, -1, -1):
                dp[i][i] = 1
                for j in range(i + 1, n):
                    dp[i][j] = dp[i + 1][j - 1] + 2 if s[i] == s[j] else max(dp[i + 1][j], dp[i][j - 1])   # wrap, or drop an end
            return dp[0][n - 1]

    Common mistakes

    • Filling by i upwards, before the inside is ready.
    • Confusing with the longest palindromic substring.

    Similar problems