VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-longest-palindromic-subsequence/

⇱ Print Longest Palindromic Subsequence - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print Longest Palindromic Subsequence

Last Updated : 20 Dec, 2022

Given a sequence, print a longest palindromic subsequence of it. 

Examples : 

Input : BBABCBCAB
Output : BABCBAB
The above output is the longest
palindromic subsequence of given
sequence. "BBBBB" and "BBCBB" are 
also palindromic subsequences of
the given sequence, but not the 
longest ones.

Input : GEEKSFORGEEKS
Output : Output can be either EEKEE
 or EESEE or EEGEE, ..

We have discussed a solution in below post to find length of longest palindromic subsequence. 
Dynamic Programming | Set 12 (Longest Palindromic Subsequence)

Method 1:

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. 

  1. Reverse the given sequence and store the reverse in another array say rev[0..n-1] 
  2. LCS of the given sequence and rev[] will be the longest palindromic sequence. 
  3. Once we have found LCS, we can print the LCS.

Below is the implementation of above approach:

Output: 
 

EEGEE

Time Complexity: O(n*m)
Auxiliary Space: O(n*m)
 

Comment
Article Tags: