{"id":26167,"date":"2017-10-26T20:11:47","date_gmt":"2017-10-26T14:41:47","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=26167"},"modified":"2017-10-26T20:11:47","modified_gmt":"2017-10-26T14:41:47","slug":"java-programming-longest-palindromic-subsequence","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-longest-palindromic-subsequence\/","title":{"rendered":"Java Programming &#8211; Longest Palindromic Subsequence"},"content":{"rendered":"<p>Given a sequence, find the length of the longest palindromic subsequence in it. For example, if the given sequence is \u201cBBABCBCAB\u201d, then the output should be 7 as \u201cBABCBAB\u201d is the longest palindromic subseuqnce in it.<span id=\"more-19155\"><\/span> \u201cBBBBB\u201d and \u201cBBCBB\u201d are also palindromic subsequences of the given sequence, but not the longest ones.<\/p>\n<p>The naive solution for this problem is to generate all subsequences of the given sequence and find the longest palindromic subsequence. This solution is exponential in term of time complexity. Let us see how this problem possesses both important properties of a Dynamic Programming (DP) Problem and can efficiently solved using Dynamic Programming.<\/p>\n<ul>\n<li><strong>Optimal Substructure: <\/strong><\/li>\n<\/ul>\n<p>Let X[0..n-1] be the input sequence of length n and L(0, n-1) be the length of the longest palindromic subsequence of X[0..n-1].<\/p>\n<p>If last and first characters of X are same, then L(0, n-1) = L(1, n-2) + 2.<br \/>\nElse L(0, n-1) = MAX (L(1, n-1), L(0, n-2)).<\/p>\n<p>Following is a general recursive solution with all cases handled.<\/p>\n<pre>\/\/ Everay single character is a palindrom of length 1\r\nL(i, i) = 1 for all indexes i in given sequence\r\n\r\n\/\/ IF first and last characters are not same\r\nIf (X[i] != X[j])  L(i, j) =  max{L(i + 1, j),L(i, j - 1)} \r\n\r\n\/\/ If there are only 2 characters and both are same\r\nElse if (j == i + 1) L(i, j) = 2  \r\n\r\n\/\/ If there are more than two characters, and first and last \r\n\/\/ characters are same\r\nElse L(i, j) =  L(i + 1, j - 1) + 2 \r\n<\/pre>\n<ul>\n<li><strong>Overlapping Subproblems<\/strong><\/li>\n<\/ul>\n<p>Following is simple recursive implementation of the LPS problem. The implementation simply follows the recursive structure mentioned above.<\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">C<\/span> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">#include&lt;stdio.h&gt;<br\/>#include&lt;string.h&gt;<br\/> <br\/>\/\/ A utility function to get max of two integers<br\/>int max (int x, int y) { return (x &gt; y)? x : y; }<br\/> <br\/>\/\/ Returns the length of the longest palindromic subsequence in seq<br\/>int lps(char *seq, int i, int j)<br\/>{<br\/>   \/\/ Base Case 1: If there is only 1 character<br\/>   if (i == j)<br\/>     return 1;<br\/> <br\/>   \/\/ Base Case 2: If there are only 2 characters and both are same<br\/>   if (seq[i] == seq[j] &amp;&amp; i + 1 == j)<br\/>     return 2;<br\/> <br\/>   \/\/ If the first and last characters match<br\/>   if (seq[i] == seq[j])<br\/>      return lps (seq, i+1, j-1) + 2;<br\/> <br\/>   \/\/ If the first and last characters do not match<br\/>   return max( lps(seq, i, j-1), lps(seq, i+1, j) );<br\/>}<br\/> <br\/>\/* Driver program to test above functions *\/<br\/>int main()<br\/>{<br\/>    char seq[] = &quot;GEEKSFORGEEKS&quot;;<br\/>    int n = strlen(seq);<br\/>    printf (&quot;The length of the LPS is %d&quot;, lps(seq, 0, n-1));<br\/>    getchar();<br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Output:<\/p>\n<pre>The length of the LPS is 5\r\n<\/pre>\n<p>Considering the above implementation, following is a partial recursion tree for a sequence of length 6 with all different characters.<\/p>\n<pre>               L(0, 5)\r\n             \/        \\ \r\n            \/          \\  \r\n        L(1,5)          L(0,4)\r\n       \/    \\            \/    \\\r\n      \/      \\          \/      \\\r\n  L(2,5)    L(1,4)  L(1,4)  L(0,3)\r\n<\/pre>\n<p>In the above partial recursion tree, L(1, 4) is being solved twice. If we draw the complete recursion tree, then we can see that there are many subproblems which are solved again and again. Since same suproblems are called again, this problem has Overlapping Subprolems property. So LPS problem has both properties of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, recomputations of same subproblems can be avoided by constructing a temporary array L[][] in bottom up manner.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Dynamic Programming Solution<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <span class=\"code-embed-name\">Java<\/span> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/A Dynamic Programming based Python Program for the Egg Dropping Puzzle<br\/>class LPS<br\/>{<br\/> <br\/>    \/\/ A utility function to get max of two integers<br\/>    static int max (int x, int y) { return (x &gt; y)? x : y; }<br\/>      <br\/>    \/\/ Returns the length of the longest palindromic subsequence in seq<br\/>    static int lps(String seq)<br\/>    {<br\/>       int n = seq.length();<br\/>       int i, j, cl;<br\/>       int L[][] = new int[n][n];  \/\/ Create a table to store results of subproblems<br\/>      <br\/>       \/\/ Strings of length 1 are palindrome of lentgh 1<br\/>       for (i = 0; i &lt; n; i++)<br\/>           L[i][i] = 1;<br\/>              <br\/>        \/\/ Build the table. Note that the lower diagonal values of table are<br\/>        \/\/ useless and not filled in the process. The values are filled in a<br\/>        \/\/ manner similar to Matrix Chain Multiplication DP solution (See<br\/>        \/\/ http:\/\/www.geeksforgeeks.org\/archives\/15553). cl is length of<br\/>        \/\/ substring<br\/>        for (cl=2; cl&lt;=n; cl++)<br\/>        {<br\/>            for (i=0; i&lt;n-cl+1; i++)<br\/>            {<br\/>                j = i+cl-1;<br\/>                if (seq.charAt(i) == seq.charAt(j) &amp;&amp; cl == 2)<br\/>                   L[i][j] = 2;<br\/>                else if (seq.charAt(i) == seq.charAt(j))<br\/>                   L[i][j] = L[i+1][j-1] + 2;<br\/>                else<br\/>                   L[i][j] = max(L[i][j-1], L[i+1][j]);<br\/>            }<br\/>        }<br\/>              <br\/>        return L[0][n-1];<br\/>    }<br\/>          <br\/>    \/* Driver program to test above functions *\/<br\/>    public static void main(String args[])<br\/>    {<br\/>        String seq = &quot;GEEKSFORGEEKS&quot;;<br\/>        int n = seq.length();<br\/>        System.out.println(&quot;The lnegth of the lps is &quot;+ lps(seq));<br\/>    }<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre>The lnegth of the LPS is 7\r\n<\/pre>\n<p>Time Complexity of the above implementation is O(n^2) which is much better than the worst case time complexity of Naive Recursive implementation.<\/p>\n<p>This problem is close to the Longest Common Subsequence (LCS) problem. In fact, we can use LCS as a subroutine to solve this problem. Following is the two step solution that uses LCS.<\/p>\n<ul>\n<li>Reverse the given sequence and store the reverse in another array say rev[0..n-1]<\/li>\n<li>LCS of the given sequence and rev[] will be the longest palindromic sequence.<br \/>\nThis solution is also a O(n^2) solution.<\/li>\n<\/ul>\n[ad type=&#8221;banner&#8221;]\n","protected":false},"excerpt":{"rendered":"<p>Java Programming &#8211; Longest Palindromic Subsequence &#8211; Dynamic Programming The solution for this problem is to generate all subsequences of the given sequence<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[69969,1,70145,2139],"tags":[72847,72842,72845,70483,72848,72840,72846,72987,72985,72843,72854,72844,72850,77578,72839,77581,73560,77593,77592,77591,77580,77579,77582,77587,73581,77594,77595,77584,72852,72855,72853,72851],"class_list":["post-26167","post","type-post","status-publish","format-standard","hentry","category-algorithm","category-coding","category-dynamic-programming","category-java","tag-concept-of-dynamic-programming","tag-define-dynamic-programming","tag-definition-of-dynamic-programming","tag-dynamic-programming","tag-dynamic-programming-code-generation-algorithm","tag-dynamic-programming-definition","tag-dynamic-programming-in-data-structure","tag-dynamic-programming-in-java","tag-dynamic-programming-java","tag-dynamic-programming-problems","tag-dynamic-programming-set-1","tag-dynamic-programming-software","tag-explain-dynamic-programming","tag-how-to-find-longest-palindromic-subsequence","tag-how-to-solve-dynamic-programming-problems","tag-longest-palindrome-substring","tag-longest-palindromic-subsequence","tag-longest-palindromic-subsequence-in-java-code","tag-longest-palindromic-subsequence-in-java-program","tag-longest-palindromic-subsequence-java","tag-longest-palindromic-subsequence-problem","tag-longest-palindromic-subsequence-using-dynamic-programming","tag-longest-palindromic-substring-in-on","tag-number-of-palindromic-subsequences","tag-palindrome-code-in-java","tag-palindrome-in-java-program","tag-palindrome-java-code","tag-print-longest-palindromic-subsequence","tag-problems-on-dynamic-programming","tag-simple-dynamic-programming-example","tag-types-of-dynamic-programming","tag-youtube-dynamic-programming"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26167","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=26167"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/26167\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=26167"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=26167"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=26167"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}