Problem of the day
You have been given a string ‘A’ consisting of lower case English letters. Your task is to find the length of the longest palindromic subsequence in ‘A’.
A subsequence is a sequence generated from a string after deleting some or no characters of the string without changing the order of the remaining string characters. (i.e. “ace” is a subsequence of “abcde” while “aec” is not).
A string is said to be palindrome if the reverse of the string is the same as the actual string. For example, “abba” is a palindrome, but “abbc” is not a palindrome.
The first line of input contains an integer ‘T’ representing the number of test cases. Then the test cases follow.
The only line of each test case contains a single string ‘A’ consisting of only lowercase English letters.
Output Format:
For each test case, print a single integer denoting the length of the longest palindromic subsequence in string ‘A’.
The output for each test case is in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10 ^ 2
Where ‘T’ is the number of test cases, and ‘N’ is the length of the string.
Time limit: 1 sec.
2
bbabcbcab
bbbab
7
4
For the first test case, the longest palindromic subsequence is “babcbab”, which has a length of 7. “bbbbb” and “bbcbb” are also palindromic subsequences of the given string, but not the longest one.
For the second test case, the longest palindromic subsequence is “bbbb”, which has a length of 4.
3
cbbd
bebeeed
abcd
2
4
1
Can you think of a recursive approach to check if the first and last characters are same or not?
The main idea behind this approach is to use recursion. The idea is to compare the first character of the string A[i..j] with its last character. There are two possibilities:
Let A[0..n-1] be the input string of length n and L(0, n-1) be the length of the longest palindromic subsequence of A[0..n-1].
If the first and last characters of A are the same, then L(0, n-1) = L(1, n-2) + 2.
Else L(0, n-1) = MAX (L(1, n-1), L(0, n-2)).
Following is a general recursive solution with all cases handled.
O(2 ^ N), where ‘N’ is the length of the given string.
In the worst case when all the characters in the given string are unique (i.e. LPS length is 1), each recursive call will end up in two recursive calls. Thus, the final time complexity is O(2 ^ N).
O(N), where ‘N’ is the length of the given string.
We are using O(H) extra space for the call stack where ‘H’ is the height of the recursion tree, and height of a recursion tree could be ‘N’ in the worst case, when all the characters present in the given string are unique (i.e. LPS length is 1). Thus, the final space complexity is O(N).