Longest palindromic subsequence

Length of the longest subsequence of a string that reads the same forwards and backwards.

Time O(n²)Space O(n²)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

A palindromic subsequence of s reads the same forwards and backwards, so it is exactly a subsequence that s shares with its own reverse. That turns the problem into the longest common subsequence of s and reverse(s), using the same diagonal-match, take-the-better-neighbour recurrence.

Code

public static int LongestPalinSubseq(string s) {
    string rev = new string(s.Reverse().ToArray());
    var dp = new int[s.Length + 1, s.Length + 1];
    for (int i = 1; i <= s.Length; i++)
        for (int j = 1; j <= s.Length; j++)
            dp[i, j] = s[i - 1] == rev[j - 1]
                ? dp[i - 1, j - 1] + 1
                : Math.Max(dp[i - 1, j], dp[i, j - 1]);
    return dp[s.Length, s.Length];
}
static int longestPalinSubseq(String s) {
    String rev = new StringBuilder(s).reverse().toString();
    int[][] dp = new int[s.length() + 1][s.length() + 1];
    for (int i = 1; i <= s.length(); i++)
        for (int j = 1; j <= s.length(); j++)
            dp[i][j] = s.charAt(i - 1) == rev.charAt(j - 1)
                ? dp[i - 1][j - 1] + 1
                : Math.max(dp[i - 1][j], dp[i][j - 1]);
    return dp[s.length()][s.length()];
}
int longestPalinSubseq(const string& s) {
    string rev(s.rbegin(), s.rend());
    int n = s.size();
    vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0));
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            dp[i][j] = s[i - 1] == rev[j - 1]
                ? dp[i - 1][j - 1] + 1
                : max(dp[i - 1][j], dp[i][j - 1]);
    return dp[n][n];
}
def longest_palin_subseq(s: str) -> int:
    rev = s[::-1]
    dp = [[0] * (len(s) + 1) for _ in range(len(s) + 1)]
    for i in range(1, len(s) + 1):
        for j in range(1, len(s) + 1):
            if s[i - 1] == rev[j - 1]:
                dp[i][j] = dp[i - 1][j - 1] + 1
            else:
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
    return dp[len(s)][len(s)]

Tips

In the .NET library

This LCS trick is neat but not the only way: a direct dp[i, j] = length of the longest palindromic subsequence inside s[i..j] also works, expanding outward from each centre or shrinking inward from the ends.