LeetCode 516: Longest Palindromic Subsequence Solution

Master LeetCode problem 516 (Longest Palindromic Subsequence), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

516. Longest Palindromic Subsequence

Problem Explanation

Explanation

To find the longest palindromic subsequence in a given string, we can use dynamic programming. We will create a 2D array dp to store the lengths of the longest palindromic subsequence for each substring. The base case would be when the length of the substring is 1, in which case the longest palindromic subsequence length would be 1.

We iterate through the string s and fill the dp array based on the following cases:

  • If s[i] == s[j], we can include both characters in the palindromic subsequence, so we add 2 to the length of the palindromic subsequence ending at i and j.
  • If s[i] != s[j], we take the maximum of the length of the palindromic subsequence ending at i-1 and j or i and j-1.

The final answer will be stored in dp[0][n-1], where n is the length of the input string.

Time Complexity: O(n^2), where n is the length of the input string. Space Complexity: O(n^2), where n is the length of the input string.

Solution Code

class Solution {
    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];
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 516 (Longest Palindromic Subsequence)?

This page provides optimized solutions for LeetCode problem 516 (Longest Palindromic Subsequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 516 (Longest Palindromic Subsequence)?

The time complexity for LeetCode 516 (Longest Palindromic Subsequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 516 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 516 in Java, C++, or Python.

Back to LeetCode Solutions