Longest Palindromic Subsequence — LeetCode 516 Python Solution
- Problem
- #516
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, find the longest palindromic subsequence's length in s. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
Example
- Input
- s = "bbbab"
- Output
- 4
- Explanation
- One possible longest palindromic subsequence is "bbbb".
Python solution
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
f = [[0] * n for _ in range(n)]
for i in range(n):
f[i][i] = 1
for i in range(n - 1, -1, -1):
for j in range(i + 1, n):
if s[i] == s[j]:
f[i][j] = f[i + 1][j - 1] + 2
else:
f[i][j] = max(f[i + 1][j], f[i][j - 1])
return f[0][-1]Complexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(n^2) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 516. Longest Palindromic Subsequence 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 516. Longest Palindromic Subsequence?
- LeetCode 516. Longest Palindromic Subsequence is rated Medium on LeetCode.
- What is the time complexity of LeetCode 516. Longest Palindromic Subsequence?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 516. Longest Palindromic Subsequence?
- The Python solution on this page uses O(n^2) auxiliary space.
- What topics does LeetCode 516. Longest Palindromic Subsequence cover?
- LeetCode 516. Longest Palindromic Subsequence is tagged String and Dynamic Programming on LeetCode.