0% found this document useful (0 votes)
272 views

Dynamic Programming - Set 12 (Longest Palindromic Subsequence) - GeeksforGeeks PDF

The document discusses finding the longest palindromic subsequence in a given sequence using dynamic programming. It explains that this problem has optimal substructure and overlapping subproblems, properties of dynamic programming problems. It then provides a recursive solution and a dynamic programming solution using a 2D table with time complexity O(n^2) to store results of subproblems and avoid recomputing them. Finally, it notes this problem is similar to the longest common subsequence problem which can also be used to find the longest palindromic subsequence.

Uploaded by

Tanisha Jindal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
272 views

Dynamic Programming - Set 12 (Longest Palindromic Subsequence) - GeeksforGeeks PDF

The document discusses finding the longest palindromic subsequence in a given sequence using dynamic programming. It explains that this problem has optimal substructure and overlapping subproblems, properties of dynamic programming problems. It then provides a recursive solution and a dynamic programming solution using a 2D table with time complexity O(n^2) to store results of subproblems and avoid recomputing them. Finally, it notes this problem is similar to the longest common subsequence problem which can also be used to find the longest palindromic subsequence.

Uploaded by

Tanisha Jindal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

DynamicProgramming|Set12
(LongestPalindromicSubsequence)
Givenasequence,findthelengthofthelongestpalindromicsubsequenceinit.
Forexample,ifthegivensequenceisBBABCBCAB,thentheoutputshould
be7asBABCBABisthelongestpalindromicsubseuqnceinit.BBBBBand
BBCBBarealsopalindromicsubsequencesofthegivensequence,butnot
thelongestones.
Thenaivesolutionforthisproblemistogenerateallsubsequencesofthegiven
sequenceandfindthelongestpalindromicsubsequence.Thissolutionis
exponentialintermoftimecomplexity.Letusseehowthisproblempossesses
bothimportantpropertiesofaDynamicProgramming(DP)Problemandcan
efficientlysolvedusingDynamicProgramming.
1)OptimalSubstructure:
LetX[0..n1]betheinputsequenceoflengthnandL(0,n1)bethelengthof
thelongestpalindromicsubsequenceofX[0..n1].
IflastandfirstcharactersofXaresame,thenL(0,n1)=L(1,n2)+2.
ElseL(0,n1)=MAX(L(1,n1),L(0,n2)).
Followingisageneralrecursivesolutionwithallcaseshandled.
//Everaysinglecharacterisapalindromoflength1
L(i,i)=1forallindexesiingivensequence
//IFfirstandlastcharactersarenotsame
If(X[i]!=X[j])L(i,j)=max{L(i+1,j),L(i,j1)}
//Ifthereareonly2charactersandbotharesame
Elseif(j==i+1)L(i,j)=2
//Iftherearemorethantwocharacters,andfirstandlast
//charactersaresame
ElseL(i,j)=L(i+1,j1)+2

2)OverlappingSubproblems
FollowingissimplerecursiveimplementationoftheLPSproblem.The
implementationsimplyfollowstherecursivestructurementionedabove.
#include<stdio.h>
#include<string.h>

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

1/4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

//Autilityfunctiontogetmaxoftwointegers
intmax(intx,inty){return(x>y)?x:y;}

//Returnsthelengthofthelongestpalindromicsubsequenceinseq
intlps(char*seq,inti,intj)
{
//BaseCase1:Ifthereisonly1character
if(i==j)
return1;

//BaseCase2:Ifthereareonly2charactersandbotharesame
if(seq[i]==seq[j]&&i+1==j)
return2;

//Ifthefirstandlastcharactersmatch
if(seq[i]==seq[j])
returnlps(seq,i+1,j1)+2;

//Ifthefirstandlastcharactersdonotmatch
returnmax(lps(seq,i,j1),lps(seq,i+1,j));
}

/*Driverprogramtotestabovefunctions*/
intmain()
{
charseq[]="GEEKSFORGEEKS";
intn=strlen(seq);
printf("ThelnegthoftheLPSis%d",lps(seq,0,n1));
getchar();
return0;
}
Output:
ThelnegthoftheLPSis5

Consideringtheaboveimplementation,followingisapartialrecursiontreefora
sequenceoflength6withalldifferentcharacters.
L(0,5)
/\
/\
L(1,5)L(0,4)
/\/\
/\/\
L(2,5)L(1,4)L(1,4)L(0,3)

Intheabovepartialrecursiontree,L(1,4)isbeingsolvedtwice.Ifwedrawthe
completerecursiontree,thenwecanseethattherearemanysubproblems
whicharesolvedagainandagain.Sincesamesuproblemsarecalledagain,
thisproblemhasOverlappingSubprolemsproperty.SoLPSproblemhasboth
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

2/4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

properties(seethisandthis)ofadynamicprogrammingproblem.Likeother
typicalDynamicProgramming(DP)problems,recomputationsofsame
subproblemscanbeavoidedbyconstructingatemporaryarrayL[][]inbottom
upmanner.
DynamicProgrammingSolution

#include<stdio.h>
#include<string.h>

//Autilityfunctiontogetmaxoftwointegers
intmax(intx,inty){return(x>y)?x:y;}

//Returnsthelengthofthelongestpalindromicsubsequenceinseq
intlps(char*str)
{
intn=strlen(str);
inti,j,cl;
intL[n][n];//Createatabletostoreresultsofsubproblems

//Stringsoflength1arepalindromeoflentgh1
for(i=0;i<n;i++)
L[i][i]=1;

//Buildthetable.Notethatthelowerdiagonalvaluesoftable
//uselessandnotfilledintheprocess.Thevaluesarefilledi
//mannersimilartoMatrixChainMultiplicationDPsolution(See
//http://www.geeksforgeeks.org/archives/15553).clislengthof
//substring
for(cl=2;cl<=n;cl++)
{
for(i=0;i<ncl+1;i++)
{
j=i+cl1;
if(str[i]==str[j]&&cl==2)
L[i][j]=2;
elseif(str[i]==str[j])
L[i][j]=L[i+1][j1]+2;
else
L[i][j]=max(L[i][j1],L[i+1][j]);
}
}

returnL[0][n1];
}

/*Driverprogramtotestabovefunctions*/
intmain()
{
charseq[]="GEEKSFORGEEKS";
intn=strlen(seq);
printf("ThelnegthoftheLPSis%d",lps(seq));
getchar();
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

3/4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

return0;
}
Output:
ThelnegthoftheLPSis7

TimeComplexityoftheaboveimplementationisO(n^2)whichismuchbetter
thantheworstcasetimecomplexityofNaiveRecursiveimplementation.
ThisproblemisclosetotheLongestCommonSubsequence(LCS)problem.In
fact,wecanuseLCSasasubroutinetosolvethisproblem.Followingisthe
twostepsolutionthatusesLCS.
1)Reversethegivensequenceandstorethereverseinanotherarraysay
rev[0..n1]
2)LCSofthegivensequenceandrev[]willbethelongestpalindromic
sequence.
ThissolutionisalsoaO(n^2)solution.
Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemore
informationaboutthetopicdiscussedabove.
References:
http://users.eecs.northwestern.edu/~dda902/336/hw6sol.pdf

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

4/4

You might also like