![]() |
VOOZH | about |
The Longest Palindromic Subsequence (LPS) is the maximum-length subsequence of a given string that is also a Palindrome. Given a string s, find the length of the Longest Palindromic Subsequence in it. A subsequence is a subset of s , with same order of elements and elements can be non adjacent.
Examples:
Input: s = "bbabcbcab"
Output: 7
Explanation: Subsequence "babcbab" , "bacbcab" is the longest subsequence which is also a palindrome.Input: s = "abcd"
Output: 1
Explanation: "a", "b", "c" and "d" are palindromic and all have a length 1.
Table of Content
The idea is to recursively generate all possible subsequences of the given string s and find the longest palindromic subsequence. To do so, create two counters low and high and set them to point to first and last character of string s. Start matching the characters from both the ends of the string. For each case, there are two possibilities:
- If characters are matching, increment the value low and decrement the value high by 1 and recur to find the LPS of new substring. And return the value result + 2.
- Else make two recursive calls for (low + 1, hi) and (lo, hi-1). And return the max of 2 calls.
7
In the above approach, lps() function is calculating the same substring multiple times. The idea is to use memoization to store the result of subproblems thus avoiding repetition.
- The size of the memo table dp[][] is going to be n x n as there are two parameters that change during recursion and range of the parameters goes from 0 to n-1.
- We initialize the memo array as -1 and in the recursive code, we make recursive call only when dp[lo][hi] is -1.
7
The above approach can be implemented using tabulation to minimize the auxiliary space required for recursive stack.
- We define a 2D table
dp, wheredp[i][j]stores the length of the longest palindromic subsequence within the substrings[i...j].- We iteratively fill the table from smaller substrings to larger ones. If the characters at both ends match, we add 2 to the result from the subsequence
s[i+1...j-1]. If they don't match, we take the maximum from excluding either the character at the start or the end.- The result for the entire string is stored in
dp[0][n-1].
7
In the above approach, for calculating the LPS of substrings starting from index i, only the LPS of substrings starting from index i+1 are required. Thus instead of creating 2d array, idea is to create two arrays of size, curr[] and prev[], where curr[j] stores the lps of substring from s[i] to s[j], while prev[j] stores the lps of substring from s[i+1] to s[j]. Else everything will be similar to above approach.
7
The idea is to reverse the given string s and find the length of the longest common subsequence of original and reversed string.