Algo-Sim › Dynamic Programming

Longest Palindromic Subsequence

Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input

Interval DP over s[i..j]: matching ends add 2 to the inside, otherwise drop one end. It equals the LCS of s and its reverse.

Problem

Given a string s, return the length of its longest palindromic subsequence: the longest palindrome you can get by deleting some characters (possibly none) without reordering the rest.

Constraints

Edge cases to test

Follow-up questions

Why does it equal LCS(s, reverse(s))?
A common subsequence of s and its reverse reads the same both ways, and the longest one is a palindrome.
What uses it?
The fewest insertions or deletions to make s a palindrome is n − LPS (LC 1312).

Solution

Java

public int longestPalindromeSubseq(String s) {
    int n = s.length();
    int[][] dp = new int[n][n];
    for (int i = n - 1; i >= 0; i--) {
        dp[i][i] = 1;
        for (int j = i + 1; j < n; j++) {
            if (s.charAt(i) == s.charAt(j)) dp[i][j] = dp[i + 1][j - 1] + 2;
            else dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
        }
    }
    return dp[0][n - 1];
}

Python

def longest_palindrome_subseq(s):
    n = len(s)
    dp = [[0] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):
        dp[i][i] = 1
        for j in range(i + 1, n):
            if 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])
    return dp[0][n - 1]

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int longestPalindromeSubseq(string &s) {
        int n = int(s.size());
        vector<vector<int>> dp(n, vector<int>(n));
        for (int i = n - 1; i >= 0; i--) {
            dp[i][i] = 1;
            for (int j = i + 1; j < n; j++) {
                if (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]);
            }
        }
        return dp[0][n - 1];
    }
};

More Dynamic Programming problems