Longest Palindromic Subsequence II — LeetCode 1682 Python Solution
- Problem
- #1682
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2 \times C) |
| Space | O(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.