Longest Palindromic Subsequence
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.
Input Format:
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.
Constraints:
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.
CodingNinjas
author
2y
Recursive Approach
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:
- If the f...read more
CodingNinjas
author
2y
DP Approach
The LPS (Longest Palindromic Subsequence) has an optimal substructure and also exhibits overlapping subproblems. Let us consider a recursion tree for a sequence of length 6 having all disti...read more
Help your peers!
Add answer anonymously...
Top MasterCard Full Stack Engineer interview questions & answers
Popular interview questions of Full Stack Engineer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app