Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Find Longest Palindromic Subsequence II
Next article icon

Longest Palindromic Subsequence in C++

Last Updated : 31 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn how to find the Longest Palindromic Subsequence (LPS) of a sequence using C++ programming language. LPS is the longest subsequence of a given sequence that reads the same backward as forward.

Example:

Input:
Sequence: "BBABCBCAB"

Output:
Length of LPS is 7

Explanation: The LPS is "BABCBAB" of length 7.
LPS
LPS Example

Approaches to Find LPS in C++ Language

  • Method 1: Using Recursion
  • Method 2: Using Memoization
  • Method 3: Using Bottom-Up (Tabulation)
  • Method 4: Using Bottom-Up (Space-Optimization)

Method 1: Using Recursion

In the recursive approach, we will generate all the possible subsequences and find the longest palindromic subsequence among them using recursion.

Approach:

  • Create a function lpsRecursive that takes a string str, and two indices i and j.
  • Base Condition: If there is only one character (i == j), return 1.
  • If there are only two characters and both are the same (str[i] == str[j]), return 2.
  • If the characters at indices i and j match (str[i] == str[j]), include both characters in LPS and recur for the remaining substring.
  • If the characters do not match, recursively find LPS by excluding one character at a time.
  • Return the maximum length obtained by including or excluding the current character.

Below is the implementation of the above approach:

C++
// C++ program to find the length of the Longest Palindromic // Subsequence (LPS) using recursion  #include <cstring> #include <iostream> using namespace std;  // Function to return the maximum of two integers int max(int a, int b) { return (a > b) ? a : b; }  // Function to find the length of the Longest Palindromic // Subsequence (LPS) using recursion int lpsRecursive(const string& str, int i, int j) {     // Base cases     if (i == j)         return 1;     if (str[i] == str[j] && i + 1 == j)         return 2;      // If characters match, include them in LPS and recur     // for remaining substring     if (str[i] == str[j])         return 2 + lpsRecursive(str, i + 1, j - 1);      // If characters do not match, recursively find LPS by     // excluding one character at a time     return max(lpsRecursive(str, i, j - 1),                lpsRecursive(str, i + 1, j)); }  int main() {     string str = "BBABCBCAB";     cout << "Length of LPS is "          << lpsRecursive(str, 0, str.length() - 1) << endl;     return 0; } 

Output
Length of LPS is 7 

Time Complexity: O(2^n)
Auxiliary Space: O(1)

Method 2: Using Memoization

We can use this optimization technique to store the results of expensive function calls and reuse them when the same inputs occur again.

Approach:

  • Create a 2D array dp of size n x n and initialize all values to -1.
  • Implement a function lpsMemoization that takes str, i, j, and the memoization array dp.
  • Base Condition: If there is only one character (i == j), return 1.
  • If the result is already computed (dp[i][j] != -1), return it.
  • If the characters at indices i and j match (str[i] == str[j]), store and return the result in the memoization array.
  • Recursively compute and store results for the remaining substrings.
  • Return the computed result from the memoization array.

Below is the implementation of the above approach:

C++
// C++ program to find the length of the Longest Palindromic // Subsequence (LPS) using Memoization  #include <cstring> #include <iostream> #include <vector> using namespace std;  // Function to return the maximum of two integers int max(int a, int b) { return (a > b) ? a : b; }  // Function to find the length of the Longest Palindromic // Subsequence (LPS) using Memoization int lpsMemoization(const string& str, int i, int j,                    vector<vector<int> >& dp) {     // Base cases     if (i == j)         return 1;     if (str[i] == str[j] && i + 1 == j)         return 2;      // If the value is already computed, return it     if (dp[i][j] != -1)         return dp[i][j];      // If characters match, include them in LPS and     // recursively find LPS for the remaining substring     if (str[i] == str[j])         return dp[i][j]                = 2 + lpsMemoization(str, i + 1, j - 1, dp);      // If characters do not match, recursively find LPS by     // excluding one character at a time     return dp[i][j]            = max(lpsMemoization(str, i, j - 1, dp),                  lpsMemoization(str, i + 1, j, dp)); }  int main() {     string str = "BBABCBCAB";     int n = str.length();     // Initialize memoization table with -1     vector<vector<int> > dp(n, vector<int>(n, -1));     cout << "Length of LPS is "          << lpsMemoization(str, 0, n - 1, dp) << endl;     return 0; } 

Output
Length of LPS is 7 

Time Complexity: O(n^2)
Auxiliary Space: O(n^2)

Method 3: Using Bottom-Up (Tabulation)

We can use the bottom-up approach by building the solution in a bottom-up manner using a table to store intermediate results.

Approach:

  • Create a 2D array dp of size n x n.
  • Set the base conditions (dp[i][i] = 1).
  • Iterate through the string, filling the table based on character matches.
  • The value at dp[0][n-1] will be the length of the LPS.

Below is the implementation of the above approach:

C++
// C++ program to find the length of the Longest Palindromic // Subsequence (LPS) using Bottom-Up (Tabulation)  #include <cstring> #include <iostream> #include <vector> using namespace std;  // Function to return the maximum of two integers int max(int a, int b) { return (a > b) ? a : b; }  // Function to find the length of the Longest Palindromic // Subsequence (LPS) using Bottom-Up (Tabulation) int lpsTabulation(const string& str) {     int n = str.length();     vector<vector<int> > dp(n, vector<int>(n, 0));      // Base cases: Single characters are palindromic     // subsequences of length 1     for (int i = 0; i < n; i++)         dp[i][i] = 1;      // Build the dp table in bottom-up manner     for (int cl = 2; cl <= n; cl++) {         for (int i = 0; i < n - cl + 1; i++) {             int j = i + cl - 1;             if (str[i] == str[j] && cl == 2)                 dp[i][j] = 2;             else if (str[i] == str[j])                 dp[i][j] = dp[i + 1][j - 1] + 2;             else                 dp[i][j] = max(dp[i][j - 1], dp[i + 1][j]);         }     }      // dp[0][n-1] contains the length of LPS for str[0..n-1]     return dp[0][n - 1]; }  int main() {     string str = "BBABCBCAB";     cout << "Length of LPS is " << lpsTabulation(str)          << endl;     return 0; } 

Output
Length of LPS is 7 

Time Complexity: O(n^2)
Auxiliary Space: O(n^2)

Method 4: Using Bottom-Up (Space-Optimization)

We can also use a space-optimized approach that reduces the space complexity of the tabulated method by using only two rows instead of a matrix.

Approach:

  • Create a 2D array dp of size 2 x n.
  • Set the base conditions (dp[0][j] = 0).
  • Iterate through the string, filling the table based on character matches using only two rows.
  • The value at dp[m % 2][n-1] will be the length of the LPS.

Below is the implementation of the above approach:

C++
// C++ program to find the length of the Longest Palindromic // Subsequence (LPS) using Bottom-Up (Space-Optimization)  #include <cstring> #include <iostream> #include <vector> using namespace std;  // Function to return the maximum of two integers int max(int a, int b) { return (a > b) ? a : b; }  // Function to find the length of the Longest Palindromic // Subsequence (LPS) using Bottom-Up (Space-Optimization) int lpsSpaceOptimized(const string& str) {     // Get the length of the input string     int n = str.length();     // Create a 2-row DP table to store results of     // subproblems     vector<vector<int> > dp(2, vector<int>(n, 0));      // Iterate over the string in reverse order     for (int i = n - 1; i >= 0; i--) {         // Each single character is a palindrome of length 1         dp[i % 2][i] = 1;         for (int j = i + 1; j < n; j++) {             // If characters match, add 2 to the result of             // the remaining substring             if (str[i] == str[j])                 dp[i % 2][j] = dp[(i + 1) % 2][j - 1] + 2;             else                 // If characters don't match, take the                 // maximum of excluding either character                 dp[i % 2][j] = max(dp[(i + 1) % 2][j],                                    dp[i % 2][j - 1]);         }     }      // The result for the entire string is stored in dp[0][n     // - 1]     return dp[0][n - 1]; }  int main() {     // Input string     string str = "BBABCBCAB";     // Output the length of the longest palindromic     // subsequence     cout << "Length of LPS is " << lpsSpaceOptimized(str)          << endl;     return 0; } 

Output
Length of LPS is 7 

Time Complexity: O(n^2)
Auxiliary Space: O(n)


Next Article
Find Longest Palindromic Subsequence II

K

kumar1amlh
Improve
Article Tags :
  • C++
  • CPP-DSA
Practice Tags :
  • CPP

Similar Reads

  • Find Longest Palindromic Subsequence II
    Given a string s, return the length of the longest good palindromic subsequence in s such that: It has an even length.No two consecutive characters are equal, except the two middle ones.Example: Input: s = "bbabab"Output: 4Explanation: The longest good palindromic subsequence of s is "baab". Input:
    8 min read
  • Longest Palindromic Subsequence in Python
    Longest Palindromic Subsequence (LPS) problem is about finding the longest subsequence of the given sequence which is a palindrome. In Python, the task of maximizing the number of words in a sentence can be solved by the methods of dynamic programming. The algorithm for finding the Longest Palindrom
    4 min read
  • Longest Increasing Subsequence in C++
    In this article, we will learn the concept of the Longest Increasing Subsequence (LIS) in a given sequence using C++ language. The LIS problem is about finding the longest subsequence of a sequence in which the elements are in sorted order, from lowest to highest, and not necessarily contiguous. Exa
    9 min read
  • Longest Increasing Subsequence in C
    In this article, we will learn how to find the Longest Increasing Subsequence (LIS) of a given sequence using C programming language. LIS is the longest subsequence of a sequence such that all elements of the subsequence are sorted in increasing order. Example: Input:Sequence: [10, 22, 9, 33, 21, 50
    9 min read
  • Length of Longest Palindrome Substring
    Given a string S of length N, the task is to find the length of the longest palindromic substring from a given string. Examples: Input: S = "abcbab"Output: 5Explanation: string "abcba" is the longest substring that is a palindrome which is of length 5. Input: S = "abcdaa"Output: 2Explanation: string
    15+ min read
  • Longest Increasing Subsequence using BIT
    Given an array arr, the task is to find the length of The Longest Increasing Sequence using Binary Indexed Tree (BIT) Examples: Input: arr = {6, 5, 1, 3, 2, 4, 8, 7} Output: 4 Explanation: The possible subsequences are {1 2 4 7}, {1 2 4 8}, {1 3 4 8}, {1 3 4 7} Now insert the elements one by one fro
    13 min read
  • Find length of repeating Substring
    Given a string s and a positive integer K, the task is to find the length of the longest contiguous substring that appears at least K times in s. Examples: Input: s = "abababcdabcd", K = 2Output: 4Explanation: "abcd" is the longest repeating substring at least K times. Input: s = "aacd", K = 4Output
    11 min read
  • Longest substring consisting of vowels using Binary Search
    Given string str of length N, the task is to find the longest substring which contains only vowels using the Binary Search technique.Examples: Input: str = "baeicba" Output: 3 Explanation: Longest substring which contains vowels only is "aei".Input: str = "aeiou" Output: 5 Approach: Refer to the Lon
    8 min read
  • Longest strictly decreasing subsequence such that no two adjacent elements are coprime
    Given an array arr[], find the length of the longest strictly decreasing subsequence such that no two adjacent elements are coprime. Examples: Input: N = 5, arr[]= {9, 6, 4, 3, 2}Output: 4Explanation: The longest strictly decreasing non-coprime subsequence is {9, 6, 4, 2} having length = 4. Input: N
    9 min read
  • Lexicographically smallest string which is not a subsequence of given string
    Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences