Longest Palindromic Subsequence II — LeetCode 1682 Python Solution

MediumLeetCode PremiumStringDynamic Programming
Problem
#1682
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

Python
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

MeasureComplexity
TimeO(n^2 \times C)
SpaceO(n·m) or optimized auxiliary

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

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.

Get Stealth Interview