Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Longest Palindromic Substring using Dynamic Programming
Next article icon

Longest Palindromic Substring using Dynamic Programming

Last Updated : 07 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first occurrence of the longest palindromic substring from left to right.

Examples:

Input: s = "aaaabbaa"
Output: "aabbaa"
Explanation: The longest palindromic substring is "aabbaa".

Input: s = "geeks" 
Output: "ee"

Input: s = "abc" 
Output: "a"

Input: s = "" 
Output: ""

Approach:

The idea is to use Dynamic Programming to store the status of smaller substrings and use these results to check if a longer substring forms a palindrome. If we know the status (i.e., palindrome or not) of the substring ranging [i, j], we can find the status of the substring ranging [i-1, j+1] by only matching the character s[i-1] and s[j+1].

  • If the substring from i to j is not a palindrome, then the substring from i-1 to j+1 will also not be a palindrome. Otherwise, it will be a palindrome only if s[i-1] and s[j+1] are the same.

Based on this fact, we can create a 2D table (say dp[][] which stores status of substring s[i...j] ), and check for substrings with length from 1 to n. For each length find all the substrings starting from each character i and find if it is a palindrome or not using the above idea. The longest length for which a palindrome formed will be the required answer.

Illustration:

Follow the below illustration for a better understanding.

Consider the string "geeks". Below is the structure of the table formed and from this, we can see that the longest substring is 2.


Step by step approach:

  1. Maintain a boolean dp[n][n] that is filled in a bottom-up manner.
  2. Fill the table initially for substrings of length = 1 and length = 2 (All substrings of length 1 are palindrome and all substrings of length 2 with same characters are also palindrome).
  3. Iterate for all possible lengths from 3 to n:
    • For each length iterate from i = 0 to n-length, find the end of the substring j = i+length-1. To calculate table[i][j], check the value of table[i+1][j-1]:
      • if the value is true and str[i] is the same as str[j], then we make table[i][j] true.
      • Otherwise, the value of table[i][j] is made false.
  4. Update the longest palindrome accordingly whenever a new palindrome of greater length is found.
C++
// C++ program to find the longest // palindromic substring. #include <bits/stdc++.h> using namespace std;  // Function to find the longest palindrome substring string longestPalindrome(string &s) {     int n = s.size();     vector<vector<bool>> dp(n, vector<bool>(n, false));          int start = 0, maxLen = 1;      // All substrings of length 1 are palindromes     for (int i = 0; i < n; ++i)         dp[i][i] = true;      // Check for sub-string of length 2     for (int i = 0; i < n - 1; ++i) {         if (s[i] == s[i + 1]) {             dp[i][i + 1] = true;             if (maxLen<2) {                 start = i;                 maxLen = 2;             }         }     }      // Check for lengths greater than 2     for (int k = 3; k <= n; ++k) {         for (int i = 0; i < n - k + 1; ++i) {             int j = i + k - 1;              if (dp[i + 1][j - 1] && s[i] == s[j]) {                 dp[i][j] = true;                  if (k > maxLen) {                     start = i;                     maxLen = k;                 }             }         }     }      return s.substr(start, maxLen); }  int main() {     string s = "aaaabbaa";     cout << longestPalindrome(s) << endl;     return 0; } 
Java
// Java program to find the longest // palindromic substring.  import java.util.*;  class GfG {      // Function to find the longest palindrome substring     static String longestPalindrome(String s) {         int n = s.length();         boolean[][] dp = new boolean[n][n];                  int start = 0, maxLen = 1;          // All substrings of length 1 are palindromes         for (int i = 0; i < n; ++i)             dp[i][i] = true;          // Check for sub-string of length 2         for (int i = 0; i < n - 1; ++i) {             if (s.charAt(i) == s.charAt(i + 1)) {                 dp[i][i + 1] = true;                 if (maxLen < 2) {                     start = i;                     maxLen = 2;                 }             }         }          // Check for lengths greater than 2         for (int k = 3; k <= n; ++k) {             for (int i = 0; i < n - k + 1; ++i) {                 int j = i + k - 1;                  if (dp[i + 1][j - 1] && s.charAt(i) == s.charAt(j)) {                     dp[i][j] = true;                      if (k > maxLen) {                         start = i;                         maxLen = k;                     }                 }             }         }          return s.substring(start, start + maxLen);     }      public static void main(String[] args) {         String s = "aaaabbaa";         System.out.println(longestPalindrome(s));     } } 
Python
# Python program to find the longest # palindromic substring.  # Function to find the longest palindrome substring def longestPalindrome(s):     n = len(s)     dp = [[False] * n for _ in range(n)]          start, maxLen = 0, 1      # All substrings of length 1 are palindromes     for i in range(n):         dp[i][i] = True      # Check for sub-string of length 2     for i in range(n - 1):         if s[i] == s[i + 1]:             dp[i][i + 1] = True             if maxLen < 2:                 start = i                 maxLen = 2      # Check for lengths greater than 2     for k in range(3, n + 1):         for i in range(n - k + 1):             j = i + k - 1              if dp[i + 1][j - 1] and s[i] == s[j]:                 dp[i][j] = True                  if k > maxLen:                     start = i                     maxLen = k      return s[start:start + maxLen]  if __name__ == "__main__":     s = "aaaabbaa"     print(longestPalindrome(s)) 
C#
// C# program to find the longest // palindromic substring.  using System;  class GfG {      // Function to find the longest palindrome substring     static string longestPalindrome(string s) {         int n = s.Length;         bool[,] dp = new bool[n, n];                  int start = 0, maxLen = 1;          // All substrings of length 1 are palindromes         for (int i = 0; i < n; ++i)             dp[i, i] = true;          // Check for sub-string of length 2         for (int i = 0; i < n - 1; ++i) {             if (s[i] == s[i + 1]) {                 dp[i, i + 1] = true;                 if (maxLen < 2) {                     start = i;                     maxLen = 2;                 }             }         }          // Check for lengths greater than 2         for (int k = 3; k <= n; ++k) {             for (int i = 0; i < n - k + 1; ++i) {                 int j = i + k - 1;                  if (dp[i + 1, j - 1] && s[i] == s[j]) {                     dp[i, j] = true;                      if (k > maxLen) {                         start = i;                         maxLen = k;                     }                 }             }         }          return s.Substring(start, maxLen);     }      static void Main(string[] args) {         string s = "aaaabbaa";         Console.WriteLine(longestPalindrome(s));     } } 
JavaScript
// JavaScript program to find the longest // palindromic substring.  // Function to find the longest palindrome substring function longestPalindrome(s) {     const n = s.length;     const dp = Array.from({ length: n }, () => Array(n).fill(false));      let start = 0, maxLen = 1;      // All substrings of length 1 are palindromes     for (let i = 0; i < n; ++i)         dp[i][i] = true;      // Check for sub-string of length 2     for (let i = 0; i < n - 1; ++i) {         if (s[i] === s[i + 1]) {             dp[i][i + 1] = true;             if (maxLen < 2) {                 start = i;                 maxLen = 2;             }         }     }      // Check for lengths greater than 2     for (let k = 3; k <= n; ++k) {         for (let i = 0; i < n - k + 1; ++i) {             const j = i + k - 1;              if (dp[i + 1][j - 1] && s[i] === s[j]) {                 dp[i][j] = true;                  if (k > maxLen) {                     start = i;                     maxLen = k;                 }             }         }     }      return s.substring(start, start + maxLen); } //Driver code  const s = "aaaabbaa"; console.log(longestPalindrome(s)); 

Output
aabbaa 

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

Related Articles:

  • Longest Palindromic Substring
  • Manacher’s Algorithm – Linear Time Longest Palindromic Substring

Next Article
Longest Palindromic Substring using Dynamic Programming

K

kartik
Improve
Article Tags :
  • Strings
  • DSA
  • Microsoft
  • Amazon
  • Groupon
  • Accolite
  • palindrome
Practice Tags :
  • Accolite
  • Amazon
  • Groupon
  • Microsoft
  • palindrome
  • Strings

Similar Reads

    Longest Palindromic Substring using Palindromic Tree | Set 3
    Given a string, find the longest substring which is a palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”. Prerequisite : Palindromic Tree | Longest Palindromic Substring Structure of Palindromic Tree : The palindromic Tree’s actual structure is clos
    15+ min read
    Distinct palindromic sub-strings of the given string using Dynamic Programming
    Given a string str of lowercase alphabets, the task is to find all distinct palindromic sub-strings of the given string. Examples: Input: str = "abaaa" Output: 5 Palindromic sub-strings are "a", "aa", "aaa", "aba" and "b" Input: str = "abcd" Output: 4 Approach: The solution to this problem has been
    8 min read
    Longest Palindromic Substring using hashing in O(nlogn)
    Given a string S, The task is to find the longest substring which is a palindrome using hashing in O(N log N) time. Input: S: ”forgeeksskeegfor”, Output: “geeksskeeg” Input: S: ”Geeks”, Output: “ee” Hashing to Solve the Problem:The hashing approach to solving the longest palindromic substring proble
    11 min read
    Longest Palindromic Substring
    Given a string s, the task is to find the longest substring which is a palindrome. If there are multiple answers, then return the first appearing substring.Examples:Input: s = "forgeeksskeegfor" Output: "geeksskeeg"Explanation: There are several possible palindromic substrings like "kssk", "ss", "ee
    12 min read
    Rearrange string to obtain Longest Palindromic Substring
    Given string str, the task is to rearrange the given string to obtain the longest palindromic substring. Examples: Input: str = “geeksforgeeks”Output: eegksfskgeeorExplanation: eegksfskgee is the longest palindromic substring after rearranging the string.Therefore, the required output is eegksfskgee
    9 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