Longest Repeating Subsequence | Practice | GeeksforGeeks

Given a string str, find the length of the longest repeating subsequence such that it can be found twice in the given string. The two identified subsequences A and B can use the same ith character from string str if and only if that ith character has different indices in A and B.
Example 1:
Input:
str = "axxzxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x z x y 
0 1 2 3 4 5

The longest subsequence is "xx". 
It appears twice as explained below.

subsequence A
x x
0 1  <-- index of subsequence A
------
1 2  <-- index of str 


subsequence B
x x
0 1  <-- index of subsequence B
------
2 4  <-- index of str 

We are able to use character 'x' 
(at index 2 in str) in both subsequences
as it appears on index 1 in subsequence A 
and index 0 in subsequence B.
Example 2:
Input:
str = "axxxy"
Output: 2
Explanation:
The given array with indexes looks like
a x x x y 
0 1 2 3 4

The longest subsequence is "xx". 
It appears twice as explained below.

subsequence A
x x
0 1  <-- index of subsequence A
------
1 2  <-- index of str 


subsequence B
x x
0 1  <-- index of subsequence B
------
2 3  <-- index of str 

We are able to use character 'x' 
(at index 2 in str) in both subsequences
as it appears on index 1 in subsequence A 
and index 0 in subsequence B.

Your Task:
You don't need to read or print anything. Your task is to complete the LongestRepeatingSubsequence() which takes str as input parameter and returns the length of the longest repeating subsequnece.

Expected Time Complexity: O(n2)
Expected Space Complexity: O(n2)

Constraints:
1 <= |str| <= 103
-129
eeshagoyal2Admin7 months ago
The problem statement has been updated to avoid any ambiguity. 
0
shishir17pandey2 weeks ago
  int call(string a,string b,int n){     int dp[1001][1001];     for(int i=0;i<n;i++){             dp[i][0]=0;     }         for(int j=0;j<n;j++){             dp[0][j]=0;         }          for(int i=1;i<=n;i++){         for(int j=1;j<=n;j++){             if(a[i-1]==b[j-1] && i!=j){                 dp[i][j]=1+dp[i-1][j-1];             }             else{                 dp[i][j]=max(dp[i-1][j],dp[i][j-1]);             }         }     }     return dp[n][n];      }int LongestRepeatingSubsequence(string str){   string a=str;   int n=str.length();   return call(a,str,n)}
;}
0
amannawal72 weeks ago
int lcs(string str1,string str2,int sz1,int sz2)    {        if(sz1<0 || sz2<0)        {            return 1;        }                if(str1[sz1]==str2[sz2] && sz1!=sz2)        {                        return lcs(str1,str2,sz1-1,sz2-1)+1;        }        else        {                        return max(lcs(str1,str2,sz1-1,sz2),lcs(str1,str2,sz1,sz2-1));        }                //how to improve TC for this code    }
+2
vr095802 weeks ago
//Not a easy level question shrm kro gfg :(
 int LongestRepeatingSubsequence(string str){     // Code here     int n=str.length(),dp[n+1][n+1];     for(int i=0;i<=n;i++){         for(int j=0;j<=n;j++){         if(i==0||j==0){             dp[i][j]=0;         }         else if(str[i-1]==str[j-1]&&i!=j) dp[i][j]=dp[i-1][j-1]+1;         else{             dp[i][j]=max(dp[i-1][j],dp[i][j-1]);         }         }     }     return dp[n][n];      }
+2
gajendrasonare3 weeks ago
Giving TLE error but why
int solve(string str, int i, int j, vector<vector<int>>dp){
	        if(i<0 || j<0) return 0;
	        
	        if(dp[i][j] != -1) return dp[i][j];
	        
	        if(str[i] == str[j] && i!=j) return dp[i][j] =  1 + solve(str,i-1,j-1,dp); 
	        
	        return dp[i][j] = max(solve(str,i-1,j,dp), solve(str,i,j-1,dp)); 
	    }
		int LongestRepeatingSubsequence(string str){
		    int n = str.length();
		    vector<vector<int>>dp(n,vector<int>(n,-1));
            return solve(str,n-1,n-1,dp); 
		}
0
jainmuskan5654 weeks ago
int dp[1001][1001];    int helper(string str1, string str2, int n,int m){        if(dp[n][m]!=-1){            return dp[n][m];        }        for(int i=0;i<=n;i++){            for(int j=0;j<=m;j++){                if(i==0 || j==0){                    dp[i][j]=0;                }            }        }        for(int i=1;i<=n;i++){            for(int j=1;j<=m;j++){                if(str1[i-1]==str2[j-1] && i!=j){                    dp[i][j]= 1+ dp[i-1][j-1];                }                else{                    dp[i][j]= max(dp[i-1][j],dp[i][j-1]);                }            }        }        return dp[n][m];    } int LongestRepeatingSubsequence(string str){     memset(dp,-1,sizeof(dp));     return helper(str,str,str.size(),str.size()); }
0
f2017084811 month ago
Can anyone tell me what is wrong in this code? it is failing for the this test case- “agcsorvauz”. It is working in my machine but not working here? why is it so. Please help me!
class Solution:def LongestRepeatingSubsequence(self,str):   # Code here       arr1=[]       count=0       maxcount=0       maxlength=0       for i in range(len(str)):           for j in range(i,len(str)):               arr1.append(str[i:j+1])       for k in range(len(arr1)):           for l in range(k+1,len(arr1)):               if arr1[k]==arr1[l]:                   length=len(arr1[k])                   if length<maxlength:                       break                   else:                       maxlength=length                       count=1                       count=count+1                   if count>maxcount:                       maxcount=count           count=0                  return maxcount
+1
officialshivaji0071 month ago
class Solution {       int dp[1001][1001];          int lcs(int x,int y,string s){           if(dp[x][y]!=-1) return dp[x][y];                      if(x==0||y==0) return dp[x][y]=0;                                 if(s[x-1]== s[y-1] && x!=y){               return dp[x][y]=1+lcs(x-1,y-1,s);           }                                 return dp[x][y]=max(lcs(x-1,y,s),lcs(x,y-1,s));       }public:    Solution(){        memset(dp,-1,sizeof(dp));    } int LongestRepeatingSubsequence(string str){     // Code here     int n = str.size();     return lcs(n,n,str);      }
};
0
vijayadurga2781 month ago
python solution:
This is one way of solution  :

class Solution:
	def LongestRepeatingSubsequence(self, str):
		# Code here
		m=len(str)
        l=[[0 for i in range(m+1)]for j in range(m+1)]
        for i in range(1,m+1):
            for  j in range(1,m+1):
                if(str[i-1]==str[j-1] and i!=j):
                    l[i][j]=l[i-1][j-1]+1
                else:
                    l[i][j]=max(l[i][j-1],l[i-1][j])
        s=''
        i=m
        j=m
        while(i>0 and j>0):
            if(l[i][j]==l[i-1][j-1]+1):
                s+=str[i-1]
                i-=1
                j-=1
            elif(l[i][j]==l[i-1][j]):
                i-=1
            else:
                j-=1
        s=''.join(reversed(s))
        return len(s)
     ------------------------------------------------------
   2)The other way is :
   class Solution:
	def LongestRepeatingSubsequence(self, str):
        n=len(str)
		p=str 
		m=[[0  for i in range(n+1)]for i in range(n+1)]
		for i in range(n+1):
		    for j in range(n+1):
		        if(i==0 or j==0):
		            m[i][j]=0
		for i in range(1,n+1):
		    for j in range(1,n+1):
		        
		        if(str[i-1]==p[j-1] and i!=j):
		            m[i][j]=m[i-1][j-1]+1
		        else:
		            m[i][j]=max(m[i-1][j],m[i][j-1])
		return m[n][n]
 
 
0
ram210320011 month ago

class Solution {
public:

int lcs(string A,string s){
     int n=A.size();
     int m=s.size();
     int t[n+1][m+1];
     for(int i=0;i<n+1;i++)
      t[i][0]=0;
      for(int j=0;j<m+1;j++)
      t[0][j]=0;
      
      for(int i=1;i<n+1;i++){
          for(int j=1;j<m+1;j++){
              if(A[i-1]==s[j-1] && (i!=j))
              t[i][j]=1+t[i-1][j-1];
              else
              t[i][j]=max(t[i][j-1],t[i-1][j]);
          }
      }
      return t[n][m];
}
 int LongestRepeatingSubsequence(string str){
     // Code here
     string A=str;
     string s=str;
     return lcs(A,s);
 }};
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.