Longest palindrome subsequence with O(n) space - GeeksforGeeks

CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems




WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


ML & Data Science
                        


Machine Learning

Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


School Learning
                        


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


For Working Professionals
                        



LIVE
                        


DSA Live Classes

System Design

Java Backend Development

Full Stack LIVE

Explore More


DSA Live Classes


System Design


Java Backend Development


Full Stack LIVE


Explore More


Self-Paced
                        


DSA- Self Paced

SDE Theory

Must-Do Coding Questions

Explore More


DSA- Self Paced


SDE Theory


Must-Do Coding Questions


Explore More


For Students
                        



LIVE
                        


Competitive Programming

Data Structures with C++

Data Science

Explore More


Competitive Programming


Data Structures with C++


Data Science


Explore More


Self-Paced
                        


DSA- Self Paced

CIP

JAVA / Python / C++

Explore More


DSA- Self Paced


CIP


JAVA / Python / C++


Explore More


School Courses
                        


School Guide

Python Programming

Learn To Make Apps

Explore more


School Guide


Python Programming


Learn To Make Apps


Explore more


Algorithms
                        


Searching Algorithms

Sorting Algorithms

Graph Algorithms

Pattern Searching

Geometric Algorithms

Mathematical

Bitwise Algorithms

Randomized Algorithms

Greedy Algorithms

Dynamic Programming

Divide and Conquer

Backtracking

Branch and Bound

All Algorithms


Searching Algorithms


Sorting Algorithms


Graph Algorithms


Pattern Searching


Geometric Algorithms


Mathematical


Bitwise Algorithms


Randomized Algorithms


Greedy Algorithms


Dynamic Programming


Divide and Conquer


Backtracking


Branch and Bound


All Algorithms


Analysis of Algorithms
                        


Asymptotic Analysis

Worst, Average and Best Cases

Asymptotic Notations

Little o and little omega notations

Lower and Upper Bound Theory

Analysis of Loops

Solving Recurrences

Amortized Analysis

What does 'Space Complexity' mean ?

Pseudo-polynomial Algorithms

Polynomial Time Approximation Scheme

A Time Complexity Question


Asymptotic Analysis


Worst, Average and Best Cases


Asymptotic Notations


Little o and little omega notations


Lower and Upper Bound Theory


Analysis of Loops


Solving Recurrences


Amortized Analysis


What does 'Space Complexity' mean ?


Pseudo-polynomial Algorithms


Polynomial Time Approximation Scheme


A Time Complexity Question


Data Structures
                        


Arrays

Linked List

Stack

Queue

Binary Tree

Binary Search Tree

Heap

Hashing

Graph

Advanced Data Structure

Matrix

Strings

All Data Structures


Arrays


Linked List


Stack


Queue


Binary Tree


Binary Search Tree


Heap


Hashing


Graph


Advanced Data Structure


Matrix


Strings


All Data Structures


Interview Corner
                        


Company Preparation

Top Topics

Practice Company Questions

Interview Experiences

Experienced Interviews

Internship Interviews

Competititve Programming

Design Patterns

System Design Tutorial

Multiple Choice Quizzes


Company Preparation


Top Topics


Practice Company Questions


Interview Experiences


Experienced Interviews


Internship Interviews


Competititve Programming


Design Patterns


System Design Tutorial


Multiple Choice Quizzes


Languages
                        


C

C++

Java

Python

C#

JavaScript

jQuery

SQL

PHP

Scala

Perl

Go Language

HTML

CSS

Kotlin


C


C++


Java


Python


C#


JavaScript


jQuery


SQL


PHP


Scala


Perl


Go Language


HTML


CSS


Kotlin


ML & Data Science
                        


Machine Learning

Data Science


Machine Learning


Data Science


CS Subjects
                        


Mathematics

Operating System

DBMS

Computer Networks

Computer Organization and Architecture

Theory of Computation

Compiler Design

Digital Logic

Software Engineering


Mathematics


Operating System


DBMS


Computer Networks


Computer Organization and Architecture


Theory of Computation


Compiler Design


Digital Logic


Software Engineering


GATE
                        


GATE Computer Science Notes

Last Minute Notes

GATE CS Solved Papers

GATE CS Original Papers and Official Keys

GATE 2021 Dates

GATE CS 2021 Syllabus

Important Topics for GATE CS


GATE Computer Science Notes


Last Minute Notes


GATE CS Solved Papers


GATE CS Original Papers and Official Keys


GATE 2021 Dates


GATE CS 2021 Syllabus


Important Topics for GATE CS


Web Technologies
                        


HTML

CSS

JavaScript

AngularJS

ReactJS

NodeJS

Bootstrap

jQuery

PHP


HTML


CSS


JavaScript


AngularJS


ReactJS


NodeJS


Bootstrap


jQuery


PHP


Software Designs
                        


Software Design Patterns

System Design Tutorial


Software Design Patterns


System Design Tutorial


School Learning
                        


School Programming


School Programming


Mathematics
                        


Number System

Algebra

Trigonometry

Statistics

Probability

Geometry

Mensuration

Calculus


Number System


Algebra


Trigonometry


Statistics


Probability


Geometry


Mensuration


Calculus


Maths Notes (Class 8-12)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes

Class 12 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


Class 12 Notes


NCERT Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


RD Sharma Solutions
                        


Class 8 Maths Solution

Class 9 Maths Solution

Class 10 Maths Solution

Class 11 Maths Solution

Class 12 Maths Solution


Class 8 Maths Solution


Class 9 Maths Solution


Class 10 Maths Solution


Class 11 Maths Solution


Class 12 Maths Solution


Physics Notes (Class 8-11)
                        


Class 8 Notes

Class 9 Notes

Class 10 Notes

Class 11 Notes


Class 8 Notes


Class 9 Notes


Class 10 Notes


Class 11 Notes


CS Exams/PSUs
                        



ISRO
                        


ISRO CS Original Papers and Official Keys

ISRO CS Solved Papers

ISRO CS Syllabus for Scientist/Engineer Exam


ISRO CS Original Papers and Official Keys


ISRO CS Solved Papers


ISRO CS Syllabus for Scientist/Engineer Exam


UGC NET
                        


UGC NET CS Notes Paper II

UGC NET CS Notes Paper III

UGC NET CS Solved Papers


UGC NET CS Notes Paper II


UGC NET CS Notes Paper III


UGC NET CS Solved Papers


Student
                        


Campus Ambassador Program

School Ambassador Program

Project

Geek of the Month

Campus Geek of the Month

Placement Course

Competititve Programming

Testimonials

Student Chapter

Geek on the Top

Internship

Careers


Campus Ambassador Program


School Ambassador Program


Project


Geek of the Month


Campus Geek of the Month


Placement Course


Competititve Programming


Testimonials


Student Chapter


Geek on the Top


Internship


Careers


Curated DSA Lists
                        


Top 50 Array Problems

Top 50 String Problems

Top 50 Tree Problems

Top 50 Graph Problems

Top 50 DP Problems


Top 50 Array Problems


Top 50 String Problems


Top 50 Tree Problems


Top 50 Graph Problems


Top 50 DP Problems


Tutorials
                        



Jobs
                        


Apply for Jobs

Post a Job

JOB-A-THON


Apply for Jobs


Post a Job


JOB-A-THON


Practice
                        


All DSA Problems

Problem of the Day

Interview Series: Weekly Contests

Bi-Wizard Coding: School Contests

Contests and Events

Practice SDE Sheet


All DSA Problems


Problem of the Day


Interview Series: Weekly Contests


Bi-Wizard Coding: School Contests


Contests and Events


Practice SDE Sheet

GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Longest Increasing Subsequence | DP-3
Coin Change | DP-7
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Sieve of Eratosthenes
Bellman–Ford Algorithm | DP-23
Matrix Chain Multiplication | DP-8
Floyd Warshall Algorithm | DP-16
Minimum number of jumps to reach end
Efficient program to print all prime factors of a given number
Edit Distance | DP-5
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Find minimum number of coins that make a given value
Top 20 Dynamic Programming Interview Questions
Overlapping Subproblems Property in Dynamic Programming | DP-1
Cutting a Rod | DP-13
Longest Common Substring | DP-29
Tabulation vs Memoization
Longest Palindromic Subsequence | DP-12
Program for nth Catalan Number
Partition a set into two subsets such that the difference of subset sums is minimum
Egg Dropping Puzzle | DP-11
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
Longest Increasing Subsequence Size (N log N)
Partition problem | DP-18
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Largest Sum Contiguous Subarray
Longest Common Subsequence | DP-4
Longest Increasing Subsequence | DP-3
Coin Change | DP-7
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Sieve of Eratosthenes
Bellman–Ford Algorithm | DP-23
Matrix Chain Multiplication | DP-8
Floyd Warshall Algorithm | DP-16
Minimum number of jumps to reach end
Efficient program to print all prime factors of a given number
Edit Distance | DP-5
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Find minimum number of coins that make a given value
Top 20 Dynamic Programming Interview Questions
Overlapping Subproblems Property in Dynamic Programming | DP-1
Cutting a Rod | DP-13
Longest Common Substring | DP-29
Tabulation vs Memoization
Longest Palindromic Subsequence | DP-12
Program for nth Catalan Number
Partition a set into two subsets such that the difference of subset sums is minimum
Egg Dropping Puzzle | DP-11
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
Longest Increasing Subsequence Size (N log N)
Partition problem | DP-18
Difficulty Level :
Hard
Given a sequence, find the length of the longest palindromic subsequence in it.
Examples:
Input : abbaab
Output : 4

Input : geeksforgeeks
Output : 5

We have discussed a Dynamic Programming solution for Longest Palindromic Subsequence which is based on below recursive formula.
// Every single character is a palindrome of length 1L(i, i) = 1 for all indexes i in given sequence
// IF first and last characters are not sameIf (X[i] != X[j]) L(i, j) = max{L(i + 1, j), L(i, j – 1)}
// If there are only 2 characters and both are sameElse if (j == i + 1) L(i, j) = 2
// If there are more than two characters, and first// and last characters are sameElse L(i, j) = L(i + 1, j – 1) + 2
The solution discussed above takes O(n2) extra space. In this post a space optimized solution is discussed that requires O(n) extra space. The idea is to create a one dimensional array a[] of same size as given string. We make sure that a[i] stores length of longest palindromic subsequence of prefix ending with i (or substring s[0..i]).
C++
Java
Python3
C#
PHP
// A Space optimized Dynamic Programming based C++// program for LPS problem#include <bits/stdc++.h>using namespace std;  // Returns the length of the longest palindromic// subsequence in strint lps(string &s){    int n = s.length();      // a[i] is going to store length of longest    // palindromic subsequence of substring s[0..i]    int a[n];      // Pick starting point    for (int i = n - 1; i >= 0; i--) {          int back_up = 0;                    // Pick ending points and see if s[i]        // increases length of longest common        // subsequence ending with s[j].        for (int j = i; j < n; j++) {              // similar to 2D array L[i][j] == 1            // i.e., handling substrings of length            // one.            if (j == i)                a[j] = 1;               // Similar to 2D array L[i][j] = L[i+1][j-1]+2            // i.e., handling case when corner characters            // are same.             else if (s[i] == s[j])            {                                  // value a[j] is depend upon previous                 // unupdated value of a[j-1] but in                 // previous loop value of a[j-1] is                 // changed. To store the unupdated                 // value of a[j-1] back_up variable                 // is used.                int temp = a[j];                a[j] = back_up + 2;                back_up = temp;            }              // similar to 2D array L[i][j] = max(L[i][j-1],            // a[i+1][j])            else            {                back_up = a[j];                a[j] = max(a[j - 1], a[j]);            }        }    }          return a[n - 1];}  /* Driver program to test above functions */int main(){    string str = "GEEKSFORGEEKS";    cout << lps(str);    return 0;}
// A Space optimized Dynamic Programming // based Java program for LPS problem  class GFG {      // Returns the length of the longest     // palindromic subsequence in str    static int lps(String s)    {        int n = s.length();      // a[i] is going to store length    // of longest palindromic subsequence    // of substring s[0..i]        int a[] = new int[n];          // Pick starting point        for (int i = n - 1; i >= 0; i--)             {            int back_up = 0;      // Pick ending points and see if s[i]    // increases length of longest common    // subsequence ending with s[j].    for (int j = i; j < n; j++) {      // similar to 2D array L[i][j] == 1    // i.e., handling substrings of length    // one.        if (j == i)        a[j] = 1;      // Similar to 2D array L[i][j] = L[i+1][j-1]+2    // i.e., handling case when corner characters    // are same.    else if (s.charAt(i) == s.charAt(j))         {        int temp = a[j];        a[j] = back_up + 2;        back_up = temp;        }      // similar to 2D array L[i][j] = max(L[i][j-1],    // a[i+1][j])      else               {                back_up = a[j];                a[j] = Math.max(a[j - 1], a[j]);            }          }    }    return a[n - 1];    }  /* Driver program to test above functions */    public static void main(String[] args)    {        String str = "GEEKSFORGEEKS";        System.out.println(lps(str));    }}  //This article is contributed by prerna saini.
# A Space optimized Dynamic Programming # based Python3 program for LPS problem  # Returns the length of the longest # palindromic subsequence in strdef lps(s):          n = len(s)      # a[i] is going to store length    # of longest palindromic subsequence    # of substring s[0..i]    a = [0] * n      # Pick starting point    for i in range(n-1, -1, -1):          back_up = 0      # Pick ending points and see if s[i]    # increases length of longest common    # subsequence ending with s[j].        for j in range(i, n):      # similar to 2D array L[i][j] == 1    # i.e., handling substrings of length    # one.            if j == i:                 a[j] = 1       # Similar to 2D array L[i][j] = L[i+1][j-1]+2    # i.e., handling case when corner characters    # are same.             elif s[i] == s[j]:                temp = a[j]                a[j] = back_up + 2                back_up = temp      # similar to 2D array L[i][j] = max(L[i][j-1],    # a[i+1][j])            else:                back_up = a[j]                a[j] = max(a[j - 1], a[j])      return a[n - 1]    # Driver Codestring = "GEEKSFORGEEKS"print(lps(string))    # This code is contributed by Ansu Kumari.
// A Space optimized Dynamic Programming // based C# program for LPS problemusing System;  class GFG {      // Returns the length of the longest     // palindromic subsequence in str    static int lps(string s)    {        int n = s.Length;      // a[i] is going to store length    // of longest palindromic subsequence    // of substring s[0..i]        int []a = new int[n];          // Pick starting point        for (int i = n - 1; i >= 0; i--)             {            int back_up = 0;      // Pick ending points and see if s[i]    // increases length of longest common    // subsequence ending with s[j].    for (int j = i; j < n; j++) {      // similar to 2D array L[i][j] == 1    // i.e., handling substrings of length    // one.        if (j == i)        a[j] = 1;      // Similar to 2D array L[i][j] = L[i+1][j-1]+2    // i.e., handling case when corner characters    // are same.    else if (s[i] == s[j])         {        int temp = a[j];        a[j] = back_up + 2;        back_up = temp;        }      // similar to 2D array L[i][j] = max(L[i][j-1],    // a[i+1][j])    else            {                back_up = a[j];                a[j] = Math.Max(a[j - 1], a[j]);            }        }    }    return a[n - 1];    }      // Driver program     public static void Main()    {        string str = "GEEKSFORGEEKS";        Console.WriteLine(lps(str));    }}  // This code is contributed by vt_m.
<?php// A Space optimized Dynamic// Programming based PHP// program for LPS problem  // Returns the length of // the longest palindromic .// subsequence in strfunction lps($s){    $n = strlen($s);      // Pick starting point    for ($i = $n - 1;          $i >= 0; $i--)     {        $back_up = 0;                  // Pick ending points and         // see if s[i] increases         // length of longest common        // subsequence ending with s[j].        for ($j = $i; $j < $n; $j++)         {              // similar to 2D array             // L[i][j] == 1 i.e.,            // handling substrings             // of length one.            if ($j == $i)                $a[$j] = 1;               // Similar to 2D array             // L[i][j] = L[i+1][j-1]+2            // i.e., handling case when             // corner characters are same.             else if ($s[$i] == $s[$j])            {                                  // value a[j] is depend                 // upon previous unupdated                 // value of a[j-1] but in                 // previous loop value of                 // a[j-1] is changed. To                 // store the unupdated value                // of a[j-1] back_up variable                 // is used.                $temp = $a[$j];                $a[$j] = $back_up + 2;                $back_up = $temp;            }              // similar to 2D array            // L[i][j] = max(L[i][j-1],            // a[i+1][j])            else            {                $back_up = $a[$j];                $a[$j] = max($a[$j - 1],                              $a[$j]);            }        }    }          return $a[$n - 1];}  // Driver Code$str = "GEEKSFORGEEKS";echo lps($str);  // This code is contributed// by shiv_bhakt.?>
5

Time Complexity : O(n*n)Auxiliary Space : O(n)YouTubeGeeksforGeeks507K subscribersLongest palindrome subsequence with O(n) space | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=i1o6rlqiSZM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Vishal_Khoda
palindrome
subsequence
Dynamic Programming
Strings
Strings
Dynamic Programming
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum size square sub-matrix with all 1s
Optimal Substructure Property in Dynamic Programming | DP-2
Optimal Binary Search Tree | DP-24
Min Cost Path | DP-6
Maximum Subarray Sum using Divide and Conquer algorithm
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack