Longest Prefix Suffix | Practice | GeeksforGeeks

Given a string of characters, find the length of the longest proper prefix which is also a proper suffix.
NOTE: Prefix and suffix can be overlapping but they should not be equal to the entire string.
Example 1:
Input: s = "abab"
Output: 2
Explanation: "ab" is the longest proper 
prefix and suffix. 
Example 2:
Input: s = "aaaa"
Output: 3
Explanation: "aaa" is the longest proper 
prefix and suffix. 
Your task:
You do not need to read any input or print anything. The task is to complete the function lps(), which takes a string as input and returns an integer. 
Expected Time Complexity: O(|s|)
Expected Auxiliary Space: O(|s|)
Constraints:
1 ≤ |s| ≤ 105
s contains lower case English alphabets
-1
sangamchoudhary72 weeks ago
class Solution{
  public:		
	int lps(string str){
	    vector<int> arr(str.size());
	    int i = 1, len = 0;
	    while(i < str.size()){
	        if(str[i] == str[len]){
	            arr[i++] = ++len;
	        }else{
	            if(len) len = arr[len-1];
	            else arr[i++] = 0;
	        }
	    }
	    return arr.back();
	}
};
0
nityabhanu2 weeks ago
A very simple yet efficient solution ,took almost half the time constraint and no new arrays and map declared
CODE:
int lps(string s) {    int count=0;    int x=0,y=1;    int flag=0;    while(y<s.length())    {       if(s[x]==s[y])       {           x++;           y++;       }       else        {           x=0;           flag++;       }       if(flag==2)       {           flag=0;           y++;       }    }    return x;}
0
prateek_jakhar2 weeks ago
JAVA SOLUTION (Constant Space Approach)
int lps(String s) {
        // code here
        int n = s.length();
        long p = 31;
        long mod = 1000000007;
        long pow = 1;
        
        long ph = 0, sh = 0;
        int ans = 0;
        for(int i = 0; i<n-1; i++){
            ph = (ph*p + (s.charAt(i)-'a'+1))%mod;
            sh = (sh + ((s.charAt(n-1-i)-'a'+1)*pow)%mod)%mod;
            pow=(pow*p)%mod;
            if(ph==sh){
                ans = i+1;
            }
        }
        return ans;
    }
+1
kshitij14103 weeks ago
int lps(string s) {   int n=s.size();      vector<int>lps(n,0);        for(int i=1;i<n;i++)   {       int j=lps[i-1];              while(j>0 and s[i]!=s[j])       j=lps[j-1];              if(s[i]==s[j]) j++;       lps[i]=j;          }         return lps[n-1];
0
jswxingyu11 month ago
Python solution
 
The running time is my bottleneck, I could barely pass it. 
 
class Solution:
    def lps(self, s):
        # code here
    
    	"""
    	# 该算法因为时间原因不能通过, 难搞哦
    	# common situation
    	for L in range(len(s)-1, 0, -1):
        	if s[0:L] == s[-L:]:
            	return L
    	return 0
    	"""    
    


        firstChar = s[0]
        indexOfNextF = 0
        lenS = len(s)
        while indexOfNextF <= lenS-1:
    
            indexOfNextF = s.find(firstChar, indexOfNextF+1)
            if indexOfNextF != -1:
                if s[:lenS-indexOfNextF] == s[indexOfNextF:]:
                    return lenS - indexOfNextF
            else:
                return 0
    
        return 0
0
ravi1010prakash1 month ago
class Solution{ public:  int lps(string str) {       int n=str.length(),len=0;       int lps[n];   lps[0]=0;   int i=1;   while(i<n){       if(str[i]==str[len])       {len++;lps[i]=len;i++;}       else       {if(len==0){lps[i]=0;i++;}           else{len=lps[len-1];}       }   }   return len;}};
// { Driver Code Starts.
int main() { 
   ios_base::sync_with_stdio(0);   cin.tie(NULL);   cout.tie(NULL);     int t;   cin >> t;   while(t--)   {    string str;    cin >> str;
    Solution ob;
    cout << ob.lps(str) << "\n";   }
   return 0;} /
-1
forworkonlydude2 months ago
Why is my code giving : Abort signal from abort(3) (SIGABRT)??
Can anyone please help me out on this? The huge test case on which it gives error is running absolutely fine, when I run it individually via custom input. PLEASE HELP GUYS!!!!
 
I am really really confused here. 
 
class Solution{
  public:		
  
  map<pair<long long,long long>,long long>mp;
  
  int matchStr(string s1, string s2, long long i, long long j){
      if(mp.find({i,j})==mp.end()){
          if(j>=s2.size()) mp[{i,j}] = 0;
          else if(s1[i]==s2[j]) mp[{i,j}] = 1+matchStr(s1,s2,i+1,j+1);
          else{
              if(i!=0){
                  j-=i;
              }
              mp[{i,j}] = matchStr(s1,s2,0,j+1)-i;
          }
      }
      return mp[{i,j}];
  }
  
	int lps(string s) {
	    // Your code goes here
	    if(s.size()<=1) return 0;
	    return matchStr(s.substr(0,s.size()-1),s.substr(1),0,0);
	  
	}
};
+3
neeramrutia2 months ago
int i=1;              for(i=1;i<s.length();i++)       {           if(s.substring(0,s.length()-i).equals(s.substring(i)))           return s.length()-i;       }       return 0;
-1
akashkhurana282 months ago
JAVA SOLUTION
class Solution {   int lps(String s) {       // code here  int n=s.length();       int [] lp=new int[n];              int len=0;       int i=1;       while (i<n){           if(s.charAt(i)==s.charAt(len)){               len++;               lp[i]=len;               i++;           }           else {               if (len==0)               {lp[i]=0;i++;}               else {                   len=lp[len-1];               }           }       }       return len;   }}
-1
kumrahulsingh75752 months ago
Easiest C++ soln in 4 lines
 
 int lps(string s) {    int m=s.length();    vector<int> lps(m,0);    for(int i=1;i<m;i++){        int j=lps[i-1];        while(j>0 && s[i]!=s[j]) j=lps[j-1];        if(s[i]==s[j]) j++;        lps[i]=j;    }    return lps[m-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.