1
+ /**
2
+ *
3
+ * Problem: Given a string of "n" characters, find the longest palindromic subsequence
4
+ * of the input string. The subsequnce can remove one or more elements from the original
5
+ * string retaining the original order of the string. This is a very different problem
6
+ * from finding the longest palindromic substring without the constraint of removing any
7
+ * elements.
8
+ *
9
+ * Use the brute force to generate all possible subsequences. While in a subsequence,
10
+ * if the string is already a palindrome from the ends, continue proceeding inwards.
11
+ * If it is not palindrome from the end, we can continue ignoring one elements from
12
+ * the left and right to see if we can achieve a palindromic subsequence.
13
+ *
14
+ * Complexity....
15
+ * Time: O(2^n) since we are making choices for recursion at each step. We choose to
16
+ * either ignore an element or to include id.
17
+ * Space: O(n) since in the worst case, we would have all the n positions opened to be
18
+ * compared.
19
+ *
20
+ * @param input
21
+ */
22
+ function findLongestPalSubseq ( input : string ) {
23
+ return findLongestPalSubseqHelper ( input , 0 , input . length - 1 ) ;
24
+ }
25
+
26
+ function findLongestPalSubseqHelper ( input : string , beg : number , end : number ) : number {
27
+
28
+ if ( end < beg ) return 0 ;
29
+ else if ( end === beg ) return 1 ;
30
+ else if ( input [ beg ] === input [ end ] ) {
31
+ // Ends are matching, continue inwards.
32
+ return 2 + findLongestPalSubseqHelper ( input , beg + 1 , end - 1 ) ;
33
+ }
34
+
35
+ // If the ends are not matching, we may try to skip an element from the end, to attempt
36
+ // to make a palindromic string
37
+ const maxWithLeftInclusion = findLongestPalSubseqHelper ( input , beg + 1 , end ) ;
38
+ const maxWithRightInclusion = findLongestPalSubseqHelper ( input , beg , end - 1 ) ;
39
+ return Math . max ( maxWithLeftInclusion , maxWithRightInclusion ) ;
40
+ }
41
+
42
+ function testLongestPlalindSubseqBF ( input : string ) {
43
+ console . log ( `Longest Palindromic Subsequence for input ${ input } : ${ findLongestPalSubseq ( input ) } ` )
44
+ }
45
+
46
+ testLongestPlalindSubseqBF ( "abdbca" )
47
+ testLongestPlalindSubseqBF ( "cddpd" )
48
+ testLongestPlalindSubseqBF ( "pqr" )
0 commit comments