Longest Palindromic Subsequence — LeetCode 516 Python Solution

MediumStringDynamic Programming
Problem
#516
Reading time
2 min

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

Python
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

MeasureComplexity
TimeO(n^2)
SpaceO(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.

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