Longest Palindromic Substring in Linear Time | Practice | GeeksforGeeks

Given a string, find the longest substring which is palindrome in Linear time O(N).
Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The only line of each test case contains a string.
Output:
For each test case print the Longest Palindromic Substring. If there are multiple such substrings of same length, print the one which appears first in the input string.
Constraints:
1 <= T <= 100
1 <= N <= 50
Example:
Input:
2
babcbabcbaccba
forgeeksskeegfor
Output:
abcbabcba
geeksskeeg
 
 
 
Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
+1
wxyzpl5 months ago
// java code
 static String LongestPalindromeSubString(String s)   {            int strLen = 2 * s.length() + 3;       char[] sChars = new char[strLen];
       /*        * To ignore special cases at the beginning and end of the array        * "abc" -> @ # a # b # c # $        * "" -> @#$        * "a" -> @ # a # $        */       sChars[0] = '@';       sChars[strLen - 1] = '$';       int t = 1;       for (char c : s.toCharArray()) {           sChars[t++] = '#';           sChars[t++] = c;       }       sChars[t] = '#';
       int maxLen = 0;       int start = 0;       int maxRight = 0;       int center = 0;       int[] p = new int[strLen]; // i's radius, which not includes i       for (int i = 1; i < strLen - 1; i++) {           if (i < maxRight) {               p[i] = Math.min(maxRight - i, p[2 * center - i]);           }
           // expand center           while (sChars[i + p[i] + 1] == sChars[i - p[i] - 1]) {               p[i]++;           }
           // update center and its bound           if (i + p[i] > maxRight) {               center = i;               maxRight = i + p[i];           }
           // update ans           if (p[i] > maxLen) {               start = (i - p[i] - 1) / 2;               maxLen = p[i];           }       }
       return s.substring(start, start + maxLen);         }} 
0
tauruas08059 months ago
string h="#";   for(int i=0;i<text.size();i++){       h.push_back(text[i]);       h.push_back('#');   }      int C=-1;   int R=-1;   int n=h.size();   vector<int>lps(n);   int imirror;      for(int i=0;i<n;i++){       imirror=2*C-i;       if(R>i){           lps[i]=min(R-i,lps[imirror]);       }       else{           lps[i]=0;       }              while((i-lps[i]-1)>=0 && (i+lps[i]+1)<n && h[i-lps[i]-1]==h[i+1+lps[i]]){           lps[i]++;       }       if(i+lps[i]>R){           R=i+lps[i];           C=i;       }   }      int mx=0;   int s;   for(int i=0;i<n;i++){       if(mx<lps[i]){           s=i;           mx=lps[i];       }   }   int l=s-mx;   int r=s+mx;   string h2=h.substr(l,r-l+1);   string ans="";   for(int i=0;i<h2.size();i++){       if(h2[i]!='#'){           ans.push_back(h2[i]);       }   }   return ans;
above code is submitted correctly but below code gives tle
 
 string text=s;       if(text.size()==1)return text;  string s1="@";  for(int i=0;i<text.size();i++)  s1=s1+'#'+text[i];  s1+='#';s1+='*';  int c=0,r=0;int lps[s1.size()+1];memset(lps,0,sizeof(lps));  for(int i=1;i<s1.size()-1;i++){      int mi=c-(i-c);      if(i<r)lps[i]=min(lps[mi],r-i);      while(i+1+lps[i]<s1.size() and i-1-lps[i]>=0 and s1[i+1+lps[i]]==s1[i-1-lps[i]])lps[i]++;      if(lps[i]+i>r){          c=i;r=lps[i]+i;      }  }  int mx=0,st=0;  for(int i=1;i<s1.size()-1;i++){      if(lps[i]>mx){mx=lps[i];st=i;}  }  int fi=st-mx+1;  int aci=(fi-2)/2;  return text.substr(aci,mx);   }   GFG LOOK INTO MATTER!!!!!
 
-1
runtime_terror11 months agoAnyone can help me in my code it show TLE    string helper(string& s, int l , int r){            int length = l==r ?-1:0;            while(l >= 0 && r < s.length() && s[l] == s[r]){                l-=1;                r+=1;                length += 2;            }            return s.substr(1+l,length);        }    string LongestPalindromeSubString(string s){        string ans = "",temp;        for(int i = 0 ; i < s.length() ; i++){            temp = helper(s,i,i);            if(ans.length() < temp.length()){                ans = temp;            }            temp = helper(s,i,i+1);            if(ans.length() < temp.length()){                ans = temp;            }        }        return ans;}Reply Open ExternallyShow 1 RepliesLoading...
runtime_terror
Anyone can help me in my code it show TLE    string helper(string& s, int l , int r){            int length = l==r ?-1:0;            while(l >= 0 && r < s.length() && s[l] == s[r]){                l-=1;                r+=1;                length += 2;            }            return s.substr(1+l,length);        }    string LongestPalindromeSubString(string s){        string ans = "",temp;        for(int i = 0 ; i < s.length() ; i++){            temp = helper(s,i,i);            if(ans.length() < temp.length()){                ans = temp;            }            temp = helper(s,i,i+1);            if(ans.length() < temp.length()){                ans = temp;            }        }        return ans;}
0
Saarth Vikram Jhaveri1 year agoManacher's algorithm gg!Reply Open ExternallyShow 1 RepliesLoading...
Saarth Vikram Jhaveri
Manacher's algorithm gg!
0
Rishabbh2 years agoMy code is causing segmentation error can someone tell mistake in it.string LongestPalindromeSubString(string text){    int n = text.length();    if(n>0)    {            int max_len=-1;        pair<int,int> p1;        p1.first=0;        p1.second=0;        int dp1[n][n];        for(int i=0;i<n;i++) {="" dp1[i][i]="1;" }="" for(int="" inc="1;inc&lt;n;inc++)" {="" for(int="" i="0;i&lt;n-inc;i++)" {="" int="" j="i+inc;" int="" c1,c2,c3="0;" if(text[i]="=text[j])" {="" int="" remain="j-i-1;" if(dp1[i+1][j-1]="=remain||remain==0)" {="" c3="2+remain;" if(c3="">max_len)                        {                            max_len=c3;                            p1.first = i;                            p1.second = j;                        }                    }                }                c1=dp1[i][j-1];                c2=dp1[i+1][j];                dp1[i][j]=max(c3,max(c1,c2));            }        }        string ans;        for(int i=p1.first;i<=p1.second;i++)            ans=ans+text[i];        return ans;    }    return "";}Reply Open ExternallyShow 0 RepliesLoading...
Rishabbh
My code is causing segmentation error can someone tell mistake in it.
string LongestPalindromeSubString(string text){
    int n = text.length();    if(n>0)    {            int max_len=-1;        pair<int,int> p1;        p1.first=0;        p1.second=0;        int dp1[n][n];        for(int i=0;i<n;i++) {="" dp1[i][i]="1;" }="" for(int="" inc="1;inc&lt;n;inc++)" {="" for(int="" i="0;i&lt;n-inc;i++)" {="" int="" j="i+inc;" int="" c1,c2,c3="0;" if(text[i]="=text[j])" {="" int="" remain="j-i-1;" if(dp1[i+1][j-1]="=remain||remain==0)" {="" c3="2+remain;" if(c3="">max_len)                        {                            max_len=c3;                            p1.first = i;                            p1.second = j;                        }                    }                }                c1=dp1[i][j-1];                c2=dp1[i+1][j];                dp1[i][j]=max(c3,max(c1,c2));            }        }        string ans;        for(int i=p1.first;i<=p1.second;i++)            ans=ans+text[i];        return ans;    }
    return "";}
0
Kunwar Sadanand2 years agohttps://ide.geeksforgeeks.o...I'm getting TLE on this code.. anyone help!Reply Open ExternallyShow 0 RepliesLoading...
Kunwar Sadanand
https://ide.geeksforgeeks.o...
I'm getting TLE on this code.. anyone help!
0
joya2 years agosimple solution just submitted  with execution time is 0.1sReply Open ExternallyShow 0 RepliesLoading...
joya
simple solution just submitted  with execution time is 0.1s
0
Krishna Swaroop2 years agoWHAT IS THIS??? IT IS SHOWING THE CORRECT OUTPUT AS WRONG.Wrong Answer. !!!Wrong AnswerPossibly your code doesn't work correctly for multiple test-cases (TCs).The first test case where your code failed:Input:zIts Correct output is:zAnd Your Code's output is:zReply Open ExternallyShow 1 RepliesLoading...
Krishna Swaroop
WHAT IS THIS??? IT IS SHOWING THE CORRECT OUTPUT AS WRONG.
Wrong Answer. !!!Wrong Answer
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:z
Its Correct output is:z
And Your Code's output is:z
0
raman mishra2 years agohttps://ide.geeksforgeeks.o...can anyone tell why its showing segmentation faultReply Open ExternallyShow 1 RepliesLoading...
raman mishra
https://ide.geeksforgeeks.o...can anyone tell why its showing segmentation fault
0
GOWTHAM G2 years agocpp solution:knowledge is to share.....https://ide.geeksforgeeks.o...Reply Open ExternallyShow 0 RepliesLoading...
GOWTHAM G
cpp solution:
knowledge is to share.....
https://ide.geeksforgeeks.o...
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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.