Longest Palindrome in a String | 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 Palindromic
substring is "aabbaa".

Example 2:
Input: 
S = "abc"
Output: a
Explanation: "a", "b" and "c" are the 
longest palindromes with same length.
The result is the one with the least
starting index.


Your Task:
You don't need to read input or print anything. Your task is to complete the function longestPalin() which takes the string S as input and returns the longest palindromic substring of S.

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

Constraints:
1 ≤ |S| ≤ 103
0
jainmuskan5655 days ago
  public: vector<vector<int>> dp; bool isPalindrome(string &s, int i,int j){     if(dp[i][j]!= -1) return dp[i][j];     else if(i<j){         if(s[i]!= s[j]) return dp[i][j]= false;         return dp[i][j]= isPalindrome(s,i+1,j-1);     }     // hidden case if i==j     return dp[i][j]=true; }   string longestPalin (string s) {       int size=0, start=0;       int n= s.size();       string ans="";       dp.resize(n,vector<int>(n,-1));       int maxsize=-1;       for(int i=0;i<n;i++){           for(int j=i+size;j<n;j++){               if(isPalindrome(s,i,j)){                   size= j-i;                   start= i;                   if(maxsize<size){                       ans=s.substr(start, size+1);                       maxsize=size;                   }               }           }       }       return ans;   }};
0
dattatraygujar776 days ago
 int n=s.length();
        boolean  dp[][]=new boolean[n][n];
        String ans="";
        for(int g=0;g<n;g++)
        {
            for(int i=0,j=g;j<n;i++,j++)
            {
               if(g==0)
               {
                   dp[i][j]=true;
               }
               else if(g==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+1][j-1]){
                      dp[i][j]=true;
                   }  
               }
               if(dp[i][j] && s.substring(i,j+1).length()>ans.length())
               {
                   ans=s.substring(i,j+1);
               }
                
            }
        }
        return ans;
+1
vishalsavade1 week ago
//0.01 time Easy method 
string longestPalin (string str) {
        // code here
        string res = "";
        int maxlength = 1, start = 0, len = 0;
        for(int i = 0; i < str.length(); i++){
            int low = i-1;
            int high = i+1;
            
            while(high < str.length() && str[i] == str[high])
                high++;
            while(low >= 0 && str[i] == str[low])
                low--;
                
            while(low >= 0 && high < str.length() && str[low] == str[high]){
                low--;
                high++;
            }
            
             len = high-low-1;
            if(len > maxlength){
                maxlength = len;
                start = low+1;
            }
        }
        
        for(int i = start; i <= start+maxlength-1; i++)
            res+=str[i];
        
        return res;
    }
-2
wishsharma0119991 week ago
java
 
0
kaustubhdwivedi17292 weeks ago
DP is ❤
string longestPalin (string s) {
        
        int n = s.size();
        
        vector<vector<int> > dp(n, vector<int>(n, 0));
        
        for(int i = 0; i < n; i++)
            dp[i][i] = 1;
        
        for(int i = 0; i < n-1; i++)
            if(s[i] == s[i+1])
                dp[i][i+1] = 2;
        
        
        for(int k = 2; k < n; k++)
            for(int i = 0; i < n-k; i++)
                if(s[i] == s[i+k] and dp[i+1][i+k-1] != 0)
                    dp[i][i+k] = dp[i+1][i+k-1] + 2;
        
        
        int maxLen = 0;
        string ans = "";
        
        for(int i = 0; i < n; i++)
            for(int j = i; j < n; j++)
                if(dp[i][j] > maxLen){
                    maxLen = dp[i][j];
                    ans = s.substr(i, maxLen);
                }
        
        return ans;
          
    }
0
kartikkeyankant2 weeks ago
C++ EASY TO UNDERSTAND , USING ODD EVEN APPROACH
 string longestPalin (string S) {
        // code here
        int s=S.size();
        int ans=0;
        string answer="";
            for(int i=0;i<s;i++){
                int x=i,y=i+1;
                while(x>=0 && y<s && S[x]==S[y]){
                    if(ans<y-x+1){
                        ans=y-x+1;
                        answer=S.substr(x,y-x+1);
                    }
                    x--;
                    y++;
                }
            

                x=i,y=i;
                while(x>=0 && y<s && S[x]==S[y]){
                    if(ans<y-x+1){
                        ans=y-x+1;
                        answer=S.substr(x,y-x+1);
                    }
                    x--;
                    y++;
                }
            }
        
    
        return answer;
    }
+1
aloksinghbais023 weeks ago
C++ solution having time complexity as O(|S|^2) and space complexity as O(|S|^2) is as follows :- 
 
Execution Time :- 0.06 / 1.12 sec
 
string longestPalin (string S) {       int n = S.length();       bool dp[n][n];       int st = 0;       int maxLen = 1;       for(int gap = 0; gap < n; gap++){           for(int i = 0, j = gap; j < n; i++,j++){               if(gap == 0){                   dp[i][j] = true;               }               else if(gap == 1){                   if(S[i] == S[j]){                       int currLen = gap + 1;                       if(currLen > maxLen){                           st = i;                           maxLen = currLen;                       }                       dp[i][j] = true;                   }                   else dp[i][j] = false;               }               else{                   if(S[i] == S[j]){                       if(dp[i+1][j-1]){                           int currLen = gap + 1;                           if(currLen > maxLen){                               st = i;                               maxLen = currLen;                           }                           dp[i][j] = true;                       }                       else dp[i][j] = false;                   }                   else dp[i][j] = false;               }           }       }              return S.substr(st,maxLen);   }
0
sunboykenneth3 weeks ago
O(n) solution with Manacher algorithm:
 
class Solution {
  private:
    string preProcessString (const string& S) {
        string newS = "@";
        for (int i = 0; i < S.length(); i++) {
            newS += S[i];
            newS += "@";
        }
        return newS;
    }
    
    vector<int> calculateRadiusArray (const string &str) {
        int n = str.length();
        if (n == 0) {
            return {};
        }
        
        vector<int> radiusArr = vector<int>(n, 0);
        int curRightMostRadius = 0, curRightMostRadiusCenter = 0;
        for (int i = 1; i < n; i++) {
            int rightMostEnd = curRightMostRadiusCenter + curRightMostRadius;

            int existingPalinRadius = 0;
            if (i < rightMostEnd) {
                int mirroredPos = 2 * curRightMostRadiusCenter - i;
                existingPalinRadius = radiusArr[mirroredPos];
                if (existingPalinRadius > rightMostEnd - i) {
                    existingPalinRadius = rightMostEnd - i;
                }
            } else {
                existingPalinRadius = 0;
            }
            
            int left = i - existingPalinRadius - 1, right = i + existingPalinRadius + 1;
            while (left >= 0 && right < n && str[left] == str[right]) {
                left--;
                right++;
                existingPalinRadius++;
            }
            
            radiusArr[i] = existingPalinRadius;
            
            if (existingPalinRadius > curRightMostRadius) {
                curRightMostRadius = existingPalinRadius;
                curRightMostRadiusCenter = i;
            }
        }
        
        return radiusArr;
    }
    
    
  public:
    string longestPalin (string S) {
        int n = S.length();
        if (n < 2) {
            return S;
        }
        
        string processedString = preProcessString(S);
        vector<int> radiusArr = calculateRadiusArray(processedString);
        
        int maxRadiusCenter = 0, maxRadius = 0;
        for (int i = 0; i < radiusArr.size(); i++) {
            if (radiusArr[i] > maxRadius) {
                maxRadius = radiusArr[i];
                maxRadiusCenter = i;
            }
        }
        
        int palinStrLen = maxRadius, palinStrStartIndex = (maxRadiusCenter - maxRadius) / 2;
        return S.substr(palinStrStartIndex, palinStrLen);
    }
};
+1
radhesh1853 weeks ago
CPP :
 bool is_palindrome(string s) {
    string rev = s;
    reverse(rev.begin(), rev.end());
    return s == rev;
}
// returns true if there is a palindrome of length x
int good(int x, string s) {
    int n = s.length();
    for(int L = 0; L + x <= n; L++) {
        if(is_palindrome(s.substr(L, x))) {
            return L;
        }
    }
    return -1;
}
  void printSubStr(string str, int low, int high)
{
    for (int i = low; i <= high; ++i)
        cout << str[i];
}
    string longestPalin (string s) {
        // code here
         int best_len = 0;
        string best_s = "";
        int n = s.length();
        for(int parity : {0, 1}) {
            int low = 1, high = n;
            if(low % 2 != parity) low++;
            if(high % 2 != parity) high--;
            while(low <= high) {
                int mid = (low + high) / 2;
                if(mid % 2 != parity) {
                    mid++;
                }
                if(mid > high) {
                    break;
                }
                int tmp = good(mid, s);
                if(tmp != -1) {
                    if(mid > best_len) {
                        best_len = mid;
                        best_s = s.substr(tmp, mid);
                    }
                    low = mid + 2;
                }
                else {
                    high = mid - 2;
                }
            }
        }
        return best_s;
        
    }
+2
technologychamp3103 weeks ago

         int n  = S.size();
        int maxlength = 1 , start = 0;
        int low , high;
        
        for(int i = 0; i < n; i++)
        {
            int low = i-1;
            int high = i+1;
            
            while(high < n && S[i] == S[high])
            high++;
            
            while(low >= 0 && S[i] == S[low])
            low--;
            
            while(high < n && low >= 0 && S[low] == S[high])
            {
                high++;
                low--;
            }
            
            int length = high - low -1;
            if(maxlength < length)
            {
                maxlength = length;
                start = low + 1;
            }
        }
        return S.substr(start , maxlength);
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.