Longest Palindromic Substring | Practice | GeeksforGeeks

Given a string S, find the longest palindromic substring in S. Substring of string S: S[ i . . . . j ] where 0 ≤ i ≤ j < len(S). Palindrome string: A string which reads the same backwards. More formally, S is palindrome if reverse(S) = S. Incase of conflict, return the substring which occurs first ( with the least starting index ).

Example 1:
Input:
S = "aaaabbaa"
Output:
aabbaa
Explanation:
The longest palindrome string present in
the given string is "aabbaa".

Your Task:  
You don't need to read input or print anything. Your task is to complete the function longestPalindrome() which takes string S as input parameters and returns longest pallindrome present in string.

Expected Time Complexity: O(|S|2)
Expected Auxiliary Space: O(1)

Constraints:
1 ≤ |S| ≤ 104
0
jy9041473 hours ago
Esay with 100%  solve by Yadav jitu
  class Solution{   String longestPalindrome(String s){     if(s.length()<2)           return s;       String longStr=s.substring(0,1);       for (int i = 0; i <s.length() ; i++) {           //check for odd string length           String tempStr=checkInput(s,i,i);           if(longStr.length()<tempStr.length())           {               longStr=tempStr;           }           //check for even string length           tempStr = checkInput(s,i,i+1);           if(longStr.length()<tempStr.length())           {               longStr=tempStr;           }       }
       return longStr;   }   public static String checkInput(String str, int left, int right){       while(left>=0 && right <str.length() && str.charAt(left)==str.charAt(right)){           left--;           right++;       }
       return str.substring(left+1,right);   }}
+1
manoj3821 week ago
class Solution{   
public:
    string longestPalindrome(string S){
        // code here 
        int ans=1,n=S.length();
        string t;
        for(int i=0;i<n;i++){
            // for odd length substring
            int a=i-1,b=i+1,temp=1;
            while(a>=0&&b<n&&S[a]==S[b]){
                a--,b++;temp+=2;
            }
            if(temp>ans){t=S.substr(a+1,temp);ans=temp;}
            //for even length substring
            
            a=i,b=i+1,temp=0;
            while(a>=0&&b<n&&S[a]==S[b]){
                a--,b++;temp+=2;
            }
            if(temp>ans){t=S.substr(a+1,temp);ans=temp;}
            
            
            
        }
         if(ans==1){t=S[0];return t;}
       return t; 
    }
};
0
getkar1281 month ago
def longestPalindrome(self, S):
       # code here
       res = ""
       resLen = 0
       for i in range(len(S)):
           # odd length
           l, r = i, i
           while l >= 0 and r < len(S) and S[l] == S[r]:
               if r-l+1 > resLen:
                   res = S[l:r+1]
                   resLen = r-l+1
               l -= 1
               r += 1
           l, r = i, i+1
           while l >= 0 and r < len(S) and S[l] == S[r]:
               if r-l+1 > resLen:
                   res = S[l:r+1]
                   resLen = r-l+1
               l -= 1
               r += 1
       return res
+2
dhruvvsingh221 month ago
Long code but simple approach ans easy to understand using 2d dp table
class Solution{   
public:
    string longestPalindrome(string str)
    {
        int n = str.length();
        int dp[n][n];
        int maxLength=1;
        int start = 0;
        int end = 0;
        for(int i=0;i<n;i++){
            for(int j=0;j<n;j++)
            {
                dp[i][j] = 0;
            }
        }
        for(int i=0;i<n;i++)
        {
            dp[i][i] = 1;
        }
        for(int i=0;i<n;i++)
        {
            if(str[i]==str[i+1])
            {
                dp[i][i+1] = 1;
                if(maxLength<2)
                {
                start = i;
                end = i+1;
                maxLength = 2;
                }
            }
        }
        for(int i=2;i<n;i++){
            for(int j=0,k=i;j<n-i,k<n;j++,k++){
                if(str[j]==str[k] && dp[j+1][k-1]==1)
                {
                    dp[j][k] = 1;
                    if(maxLength<abs(k-j+1))
                    {
                    start = j;
                    end = k;
                    maxLength = max(maxLength,abs(k-j+1));
                    }
                }
            }
        }
        return str.substr(start,end-start+1);
    }
};
+1
madhukartemba1 month ago
JAVA SOLUTION:
SOURCE: https://www.youtube.com/watch?v=WpYHNHofwjc
String longestPalindrome(String S){
        // code here
        int n = S.length();
        
        boolean dp[][] = new boolean[n][n];
        
        int max_len = 1;
        
        int st = 0, en = 0;
        
        for(int gap=0; gap<n; gap++)
        {
            for(int i=0, j=gap; j<n; j++, i++)
            {
                if(gap==0)
                {
                    dp[i][j] = true;
                }
                else if(gap==1)
                {
                    if(S.charAt(i)==S.charAt(j))
                    {
                        dp[i][j] = true;
                    }
                    else
                    {
                        dp[i][j] = false;
                    }
                }
                else
                {
                    if(S.charAt(i)==S.charAt(j))
                    {
                        dp[i][j] = dp[i+1][j-1];
                    }
                    else
                    {
                        dp[i][j] = false;
                    }
                    
                }
                
                if(dp[i][j] == true)
                {
                    //System.out.println(i + " " + j);
                    if(gap+1>max_len)
                    {
                        st = i;
                        en = j;
                        max_len = gap+1;
                    }
                    else if(gap+1==max_len)
                    {
                        if(i<st)
                        {
                            st = i;
                            gap = j;
                        }
                    }
                }
            }
        }
        
        return S.substring(st, en+1);
        
        
        
    }
-1
sudarshanp49122 months ago
EASY TO UNDERSTAND SOLUTION:
bool isPalindrome(string str)
    {
        int n=str.length();
        for(int i=0;i<n/2;i++)
        {
            if(str[i]!=str[n-1-i])
            return false;
        }
        return true;
    }
    
    string longestPalindrome(string S)
    {
        if(isPalindrome(S))
        return S;
        
        int n=S.length(),ans=0;
        string sol;
        
        for(int i=0;i<n;i++)
        {
            for(int j=i;j<n;j++)
            {
                string str=S.substr(i,j-i+1);
                
                if(isPalindrome(str))
                {
                    int len=str.length();
                    if(len>ans)
                    {
                        ans=len;
                        sol=str;
                    }
                }
            }
        }
        return sol;
    }
0
mikumar2 months ago
class Solution{   public static boolean pal(String s)   {   int l =0 ;    int h = s.length()-1;   while(l<h)   {       if(s.charAt(l)!=s.charAt(h))       return false;       l++;       h--;   }   return true;   }      String longestPalindrome(String s){     ArrayList<String>al = new ArrayList<>();       for(int i =0 ; i<s.length() ; i++){           for(int j = i+1 ; j<=s.length(); j++){               al.add(s.substring(i , j));           }       }       String msi ="";       int maxi=-1;       for(int i =0 ; i<al.size();i++)       {           if(pal(al.get(i))==true)           {               if(al.get(i).length()>maxi)               {                   maxi = al.get(i).length();                   msi = al.get(i);               }           }       }       return msi;   }} 
+1
dassdazzer1232 months ago
TC-→O(n2)  || SC-→ O(1)
 
string longestPalindrome(string S){       if(S.length()<=1) return S;       int mx_len=1;       int n=S.length();       int start=0,end=0;              //odd length palindrome       for(int i=0;i<n;i++)       {           int l=i,r=i;           while(l>=0 && r<n)           {               if(S[l]==S[r])               {                   l--;                   r++;               }               else               break;           }           int len=r-l-1;           if(len>mx_len)           {               mx_len=len;               start=l+1;               end=r-1;           }       }                     //Even length palindrome       for(int i=0;i<n;i++)       {           int l=i,r=i+1;           while(l>=0 && r<n)           {               if(S[l]==S[r])               {                   l--;                   r++;               }               else               break;           }           int len=r-l-1;           if(len>mx_len)           {               mx_len=len;               start=l+1;               end=r-1;           }       }              return S.substr(start,mx_len);   }
0
tanishqspike1142 months ago
C++ Code | O(N^2) Time and O(1) Space Solution
class Solution{   
private:
    pair<int,int> expand(string &S,int L,int R){
        while(L>=0 and R<S.length() and S[L]==S[R]){
            L--;
            R++;
        }
        if(S[L]!=S[R]){
            L++;
            R--;
        }
        return {L,R};
    }
public:
    string longestPalindrome(string S){
        /*
            Using the property that a panlindrom mirrors from its center we try to expand from everypoint
            and from everypoint we will try to go as many spaces in right and left till they both are equal
        */
        using paint=pair<int,int>;
        int start=0,end=0,n=S.length()-1;
        for(int i=0;i<n;i++){
            paint a=expand(S,i,i);
            paint b=expand(S,i,i+1);
            paint final = a.second-a.first>b.second-b.first?a:b;
            if(final.second-final.first>end-start){
                start=final.first;
                end=final.second;
            }
        }
        start=max(0,start);
        end=min(n,end);
        return S.substr(start,end-start+1);
    }
};
+2
navidulhaque2 months ago
TC-O(n)^2 .... SC-O(n)^2for better understanding watch pepcoding's video
string longestPalindrome(string s){
        int n=s.size();
        int dp[n][n];
        memset(dp,0,sizeof(dp));
        int ans=INT_MIN;
        int st=0;
        int en=0;
        string res;
        for(int gap=0;gap<n;gap++){
            for(int i=0,j=gap;j<n;j++,i++){
                if(gap==0){
                    dp[i][j]=1;
                }
                else if(gap==1){
                    dp[i][j]=s[i]==s[j]?1:0;
                }
                else{
                    dp[i][j]=s[i]==s[j]?dp[i+1][j-1]:0;
                }
                if(ans<j-i&&dp[i][j]==1){
                    ans=j-i;
                    st=i;
                    en=j-i;
                }
            }
        }
        return s.substr(st,en+1);
    }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.