MediumNo. 1682LeetCode Premium

Longest Palindromic Subsequence II — LeetCode 1682 Python Solution

Topics
String, Dynamic Programming
Reading time
2 min

The problem

A subsequence of a string s is considered a good palindromic subsequence if: It is a subsequence of s. It is a palindrome (has the same value if reversed).

Example

Input
s = "bbabab"
Output
4
Explanation
The longest good palindromic subsequence of s is "baab".

Python solution

PythonSolution
class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        @cache
        def dfs(i, j, x):
            if i >= j:
                return 0
            if s[i] == s[j] and s[i] != x:
                return dfs(i + 1, j - 1, s[i]) + 2
            return max(dfs(i + 1, j, x), dfs(i, j - 1, x))

        ans = dfs(0, len(s) - 1, '')
        dfs.cache_clear()
        return ans

Complexity

Time
O(n2 × C)
Space · auxiliary
O(n·m)or optimized

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1682. Longest Palindromic Subsequence II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0516Longest Palindromic SubsequenceMedium
0010Regular Expression MatchingHard
0022Generate ParenthesesMedium
0032Longest Valid ParenthesesHard
0044Wildcard MatchingHard
0072Edit DistanceMedium

Frequently asked questions

How hard is LeetCode 1682. Longest Palindromic Subsequence II?

LeetCode 1682. Longest Palindromic Subsequence II is rated Medium on LeetCode.

What topics does LeetCode 1682. Longest Palindromic Subsequence II cover?

LeetCode 1682. Longest Palindromic Subsequence II is tagged String and Dynamic Programming on LeetCode.

Is LeetCode 1682. Longest Palindromic Subsequence II a premium problem?

Yes. LeetCode 1682. Longest Palindromic Subsequence II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.