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
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Minimum Characters to Add at Front for Palindrome
Next article icon

Longest Palindromic Substring

Last Updated : 10 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 appearing substring.

Examples:

Input: s = “forgeeksskeegfor” 
Output: “geeksskeeg”
Explanation: There are several possible palindromic substrings like “kssk”, “ss”, “eeksskee” etc. But the substring “geeksskeeg” is the longest among all.

Input: s = “Geeks” 
Output: “ee”

Input: s = “abc” 
Output: “a”

Input: s = “” 
Output: “”

Table of Content

  • [Naive Approach] Generating all sub-strings – O(n^3) time and O(1) space
  • [Better Approach] Using Dynamic Programming – O(n^2) time and O(n^2) space
  • [Better Approach] Using Expansion from center – O(n^2) time and O(1) space
  • [Expected Approach] Using Manacher’s Algorithm – O(n) time and O(n) space

[Naive Approach] Generating all sub-strings – O(n^3) time and O(1) space

The idea is to generate all substrings.

  • For each substring, check if it is palindrome or not.
  • If substring is Palindrome, then update the result on the basis of longest palindromic substring found till now.
C++
#include <bits/stdc++.h> using namespace std;  // Function to check if a substring  // s[low..high] is a palindrome bool checkPal(string &s, int low, int high) {     while (low < high) {         if (s[low] != s[high])             return false;         low++;         high--;     }     return true; }  // function to find the longest palindrome substring string longestPalindrome(string& s) {        // Get length of input string     int n = s.size();      // All substrings of length 1 are palindromes     int maxLen = 1, start = 0;      // Nested loop to mark start and end index     for (int i = 0; i < n; i++) {         for (int j = i; j < n; j++) {                        // Check if the current substring is              // a palindrome             if (checkPal(s, i, j) && (j - i + 1) > maxLen) {                 start = i;                 maxLen = j - i + 1;             }         }     }      return s.substr(start, maxLen); }  int main() {     string s = "forgeeksskeegfor";     cout << longestPalindrome(s) << endl;     return 0; } 
Java
// Java program to find the longest // palindromic substring.  import java.util.*;  class GfG {      // Function to check if a substring      // s[low..high] is a palindrome     static boolean checkPal(String s, int low, int high) {         while (low < high) {             if (s.charAt(low) != s.charAt(high))                 return false;             low++;             high--;         }         return true;     }      // Function to find the longest palindrome substring     static String longestPalindrome(String s) {          // Get length of input string         int n = s.length();          // All substrings of length 1 are palindromes         int maxLen = 1, start = 0;          // Nested loop to mark start and end index         for (int i = 0; i < n; i++) {             for (int j = i; j < n; j++) {                  // Check if the current substring is                  // a palindrome                 if (checkPal(s, i, j) && (j - i + 1) > maxLen) {                     start = i;                     maxLen = j - i + 1;                 }             }         }          return s.substring(start, start + maxLen);     }      public static void main(String[] args) {         String s = "forgeeksskeegfor";         System.out.println(longestPalindrome(s));     } } 
Python
# Python program to find the longest # palindromic substring.  # Function to check if a substring  # s[low..high] is a palindrome def checkPal(str, low, high):     while low < high:         if str[low] != str[high]:             return False         low += 1         high -= 1     return True  # Function to find the longest palindrome substring def longestPalindrome(s):          # Get length of input string     n = len(s)      # All substrings of length 1 are palindromes     maxLen = 1     start = 0      # Nested loop to mark start and end index     for i in range(n):         for j in range(i, n):              # Check if the current substring is              # a palindrome             if checkPal(s, i, j) and (j - i + 1) > maxLen:                 start = i                 maxLen = j - i + 1      return s[start:start + maxLen]  if __name__ == "__main__":     s = "forgeeksskeegfor"     print(longestPalindrome(s)) 
C#
// C# program to find the longest // palindromic substring.  using System;  class GfG {      // Function to check if a substring      // s[low..high] is a palindrome     static bool checkPal(string s, int low, int high) {         while (low < high) {             if (s[low] != s[high])                 return false;             low++;             high--;         }         return true;     }      // Function to find the longest palindrome substring     static string longestPalindrome(string s) {          // Get length of input string         int n = s.Length;          // All substrings of length 1 are palindromes         int maxLen = 1, start = 0;          // Nested loop to mark start and end index         for (int i = 0; i < n; i++) {             for (int j = i; j < n; j++) {                  // Check if the current substring is                  // a palindrome                 if (checkPal(s, i, j) && (j - i + 1) > maxLen) {                     start = i;                     maxLen = j - i + 1;                 }             }         }          return s.Substring(start, maxLen);     }      static void Main(string[] args) {         string s = "forgeeksskeegfor";         Console.WriteLine(longestPalindrome(s));     } } 
JavaScript
// JavaScript program to find the longest // palindromic substring.  // Function to check if a substring  // s[low..high] is a palindrome function checkPal(s, low, high) {     while (low < high) {         if (s[low] !== s[high])             return false;         low++;         high--;     }     return true; }  // Function to find the longest palindrome substring function longestPalindrome(s) {      // Get length of input string     const n = s.length;      // All substrings of length 1 are palindromes     let maxLen = 1, start = 0;      // Nested loop to mark start and end index     for (let i = 0; i < n; i++) {         for (let j = i; j < n; j++) {              // Check if the current substring is              // a palindrome             if (checkPal(s, i, j) && (j - i + 1) > maxLen) {                 start = i;                 maxLen = j - i + 1;             }         }     }      return s.substring(start, start + maxLen); }  // Driver Code const s = "forgeeksskeegfor"; console.log(longestPalindrome(s)); 

Output
geeksskeeg 

[Better Approach – 1] Using Dynamic Programming – O(n^2) time and O(n^2) space

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.

  • The main idea behind the approach is that 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 str[i-1] and str[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 str[i-1] and str[j+1] are the same.
  • Base on this fact, we can create a 2D table (say table[][] which stores status of substring str[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 palindrom or not using the above idea. The longest length for which a palindrome formed will be the required asnwer.

Note: Refer to Longest Palindromic Substring using Dynamic Programming for detailed approach and code.

[Better Approach – 2] Using Expansion from center – O(n^2) time and O(1) space

The idea is to traverse each character in the string and treat it as a potential center of a palindrome, trying to expand around it in both directions while checking if the expanded substring remains a palindrome.

  • For each position, we check for both odd-length palindromes (where the current character is the center) and even-length palindromes (where the current character and the next character together form the center).
  • As we expand outward from each center, we keep track of the start position and length of the longest palindrome found so far, updating these values whenever we find a longer valid palindrome.

Step-by-step approach:

  • Use two pointers, low and hi, for the left and right end of the current palindromic substring being found. 
  • Then checks if the characters at s[low] and s[hi] are the same. 
    • If they are, it expands the substring to the left and right by decrementing low and incrementing hi. 
    • It continues this process until the characters at s[low] and s[hi] are unequal or until the indices are in bounds.
  • If the length of the current palindromic substring becomes greater than the maximum length, it updates the maximum length.
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.length();     if (n == 0) return "";      int start = 0, maxLen = 1;      // Traverse the input string     for (int i = 0; i < n; i++) {          // THIS RUNS TWO TIMES          // for both odd and even length         // palindromes. j = 0 means odd         // and j = 1 means even length         for (int j = 0; j <= 1; j++) {             int low = i;             int high = i + j;               // Expand substring while it is a palindrome             // and in bounds             while (low >= 0 && high < n && s[low] == s[high]) {                 int currLen = high - low + 1;                 if (currLen > maxLen) {                     start = low;                     maxLen = currLen;                 }                 low--;                 high++;             }         }     }      return s.substr(start, maxLen); }  int main() {     string s = "forgeeksskeegfor";     cout << longestPalindrome(s) << endl;     return 0; } 
Java
// Java program to find the longest // palindromic substring.  class GfG {      // Function to find the longest palindrome substring     static String longestPalindrome(String s) {         int n = s.length();         if (n == 0) return "";          int start = 0, maxLen = 1;          // Traverse the input string         for (int i = 0; i < n; i++) {              // THIS RUNS TWO TIMES              // for both odd and even length             // palindromes. j = 0 means odd             // and j = 1 means even length             for (int j = 0; j <= 1; j++) {                 int low = i;                 int high = i + j;                   // Expand substring while it is a palindrome                 // and in bounds                 while (low >= 0 && high < n && s.charAt(low) == s.charAt(high)) {                     int currLen = high - low + 1;                     if (currLen > maxLen) {                         start = low;                         maxLen = currLen;                     }                     low--;                     high++;                 }             }         }          return s.substring(start, start + maxLen);     }      public static void main(String[] args) {         String s = "forgeeksskeegfor";         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)     if n == 0:         return ""      start, maxLen = 0, 1      # Traverse the input string     for i in range(n):          # THIS RUNS TWO TIMES          # for both odd and even length         # palindromes. j = 0 means odd         # and j = 1 means even length         for j in range(2):             low, high = i, i + j              # Expand substring while it is a palindrome             # and in bounds             while low >= 0 and high < n and s[low] == s[high]:                 currLen = high - low + 1                 if currLen > maxLen:                     start = low                     maxLen = currLen                 low -= 1                 high += 1      return s[start:start + maxLen]  if __name__ == "__main__":     s = "forgeeksskeegfor"     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;         if (n == 0) return "";          int start = 0, maxLen = 1;          // Traverse the input string         for (int i = 0; i < n; i++) {              // THIS RUNS TWO TIMES              // for both odd and even length             // palindromes. j = 0 means odd             // and j = 1 means even length             for (int j = 0; j <= 1; j++) {                 int low = i;                 int high = i + j;                   // Expand substring while it is a palindrome                 // and in bounds                 while (low >= 0 && high < n && s[low] == s[high]) {                     int currLen = high - low + 1;                     if (currLen > maxLen) {                         start = low;                         maxLen = currLen;                     }                     low--;                     high++;                 }             }         }          return s.Substring(start, maxLen);     }      static void Main(string[] args) {         string s = "forgeeksskeegfor";         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;     if (n === 0) return "";      let start = 0, maxLen = 1;      // Traverse the input string     for (let i = 0; i < n; i++) {          // THIS RUNS TWO TIMES          // for both odd and even length         // palindromes. j = 0 means odd         // and j = 1 means even length         for (let j = 0; j <= 1; j++) {             let low = i;             let high = i + j;               // Expand substring while it is a palindrome             // and in bounds             while (low >= 0 && high < n && s[low] === s[high]) {                 const currLen = high - low + 1;                 if (currLen > maxLen) {                     start = low;                     maxLen = currLen;                 }                 low--;                 high++;             }         }     }      return s.substring(start, start + maxLen); }  // Driver Code const s = "forgeeksskeegfor"; console.log(longestPalindrome(s)); 

Output
geeksskeeg 

[Expected Approach] Using Manacher’s Algorithm – O(n) time and O(n) space

We can solve this problem in linear time using Manacher’s Algorithm. Refer the below links for details:

  • Manacher’s Algorithm – Part 1
  • Manacher’s Algorithm – Part 2
  • Manacher’s Algorithm – Part 3




Next Article
Minimum Characters to Add at Front for Palindrome
author
kartik
Improve
Article Tags :
  • DSA
  • Dynamic Programming
  • Strings
  • Accolite
  • Amazon
  • Groupon
  • MakeMyTrip
  • Microsoft
  • Qualcomm
  • Samsung
  • strings
  • Visa
  • Zoho
Practice Tags :
  • Accolite
  • Amazon
  • Groupon
  • MakeMyTrip
  • Microsoft
  • Qualcomm
  • Samsung
  • Visa
  • Zoho
  • Dynamic Programming
  • Strings
  • Strings

Similar Reads

  • Palindrome String Coding Problems
    A string is called a palindrome if the reverse of the string is the same as the original one. Example: “madam”, “racecar”, “12321”. Properties of a Palindrome String:A palindrome string has some properties which are mentioned below: A palindrome string has a symmetric structure which means that the
    2 min read
  • Palindrome String
    Given a string s, the task is to check if it is palindrome or not. Example: Input: s = "abba"Output: 1Explanation: s is a palindrome Input: s = "abc" Output: 0Explanation: s is not a palindrome Using Two-Pointers - O(n) time and O(1) spaceThe idea is to keep two pointers, one at the beginning (left)
    14 min read
  • Check Palindrome by Different Language

    • Palindrome Number Program in C
      Write a C program to check whether a given number is a palindrome or not. Palindrome numbers are those numbers which after reversing the digits equals the original number. Examples Input: 121Output: YesExplanation: The number 121 remains the same when its digits are reversed. Input: 123Output: NoExp
      4 min read

    • C Program to Check for Palindrome String
      A string is said to be palindrome if the reverse of the string is the same as the string. In this article, we will learn how to check whether the given string is palindrome or not using C program. The simplest method to check for palindrome string is to reverse the given string and store it in a tem
      4 min read

    • C++ Program to Check if a Given String is Palindrome or Not
      A string is said to be palindrome if the reverse of the string is the same as the original string. In this article, we will check whether the given string is palindrome or not in C++. Examples Input: str = "ABCDCBA"Output: "ABCDCBA" is palindromeExplanation: Reverse of the string str is "ABCDCBA". S
      4 min read

    • Java Program to Check Whether a String is a Palindrome
      A string in Java can be called a palindrome if we read it from forward or backward, it appears the same or in other words, we can say if we reverse a string and it is identical to the original string for example we have a string s = "jahaj " and when we reverse it s = "jahaj"(reversed) so they look
      8 min read

    Easy Problems on Palindrome

    • Sentence Palindrome
      Given a sentence s, the task is to check if it is a palindrome sentence or not. A palindrome sentence is a sequence of characters, such as a word, phrase, or series of symbols, that reads the same backward as forward after converting all uppercase letters to lowercase and removing all non-alphanumer
      9 min read
    • Check if actual binary representation of a number is palindrome
      Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Inp
      6 min read
    • Print longest palindrome word in a sentence
      Given a string str, the task is to print longest palindrome word present in the string str.Examples: Input : Madam Arora teaches Malayalam Output: Malayalam Explanation: The string contains three palindrome words (i.e., Madam, Arora, Malayalam) but the length of Malayalam is greater than the other t
      14 min read
    • Count palindrome words in a sentence
      Given a string str and the task is to count palindrome words present in the string str. Examples: Input : Madam Arora teaches malayalam Output : 3 The string contains three palindrome words (i.e., Madam, Arora, malayalam) so the count is three. Input : Nitin speaks malayalam Output : 2 The string co
      5 min read
    • Check if characters of a given string can be rearranged to form a palindrome
      Given a string, Check if the characters of the given string can be rearranged to form a palindrome. For example characters of "geeksogeeks" can be rearranged to form a palindrome "geeksoskeeg", but characters of "geeksforgeeks" cannot be rearranged to form a palindrome. Recommended PracticeAnagram P
      14 min read
    • Lexicographically first palindromic string
      Rearrange the characters of the given string to form a lexicographically first palindromic string. If no such string exists display message "no palindromic string". Examples: Input : malayalam Output : aalmymlaa Input : apple Output : no palindromic string Simple Approach: 1. Sort the string charact
      13 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