Longest Palindromic Subsequence Problem
Description
LeetCode Problem 516.
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 1:
Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".
Example 2:
Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".
Constraints:
- 1 <= s.length <= 1000
- s consists only of lowercase English letters.
Solution
Approach: Interval Dynamic Programming
Trying every subsequence takes 2n steps. Instead, look at the two ends of a substring: a palindrome's first and last characters are equal, so the ends decide how the answer for s[i..j] is built from answers for shorter substrings.
Let longest[i][j] be the length of the longest palindromic subsequence of s[i..j].
- A single character is a palindrome:
longest[i][i] = 1. - If
s[i] == s[j], both ends can wrap the best palindrome inside:longest[i][j] = longest[i + 1][j - 1] + 2. - Otherwise the two ends cannot both be used, so drop one of them:
longest[i][j] = max(longest[i + 1][j], longest[i][j - 1]).
The answer is longest[0][n - 1].
The loop order matters: longest[i][j] reads row i + 1, so i must go from n - 1 down to 0, with j going up from i + 1. For two equal neighbours (j = i + 1), the inside part s[i + 1..i] is empty; the table starts at 0, so that cell correctly gives 2.
Example 2, "cbbd": longest[1][2] = 2 because s[1] == s[2] == 'b'. No longer substring has matching ends, so the value 2 carries up to longest[0][3].
Complexity: O(n2) time and O(n2) space, where n is the length of s.
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
n = len(s)
# longest[i][j] = length of the longest palindromic subsequence of s[i..j].
longest = [[0] * n for _ in range(n)]
# i goes down so that longest[i + 1][...] is ready before row i needs it.
for i in range(n - 1, -1, -1):
longest[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]:
# Both ends match: they wrap the best answer of the inside part.
longest[i][j] = longest[i + 1][j - 1] + 2
else:
# Drop one of the two ends.
longest[i][j] = max(longest[i + 1][j], longest[i][j - 1])
return longest[0][n - 1]
Now write it from memory
Close the write-up and solve it yourself against the tests.