Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com

Longest Palindromic Subsequence

Hard
0/120
Average time to solve is 45m
profile
Contributed by
80 upvotes
Asked in companies
Tata 1mgCIS - Cyber InfrastructureIBM

Problem statement

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.

Detailed explanation ( Input/output format, Notes, Images )
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.
Sample Input 1:
2
bbabcbcab
bbbab
Sample Output 1:
7
4
Explanation of Sample Input 1:
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.
Sample Input 2:
3
cbbd
bebeeed
abcd
Sample Output 2:
2
4
1
Full screen
Console