Longest Common Subsequence | Practice | GeeksforGeeks

Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.
Example 1:
Input:
A = 6, B = 6
str1 = ABCDGH
str2 = AEDFHR
Output: 3
Explanation: LCS for input Sequences
“ABCDGH” and “AEDFHR” is “ADH” of
length 3.

Example 2:
Input:
A = 3, B = 2
str1 = ABC
str2 = AC
Output: 2
Explanation: LCS of "ABC" and "AC" is
"AC" of length 2.
Your Task:
Complete the function lcs() which takes the length of two strings respectively and two strings as input parameters and returns the length of the longest subsequence present in both of them. 
Expected Time Complexity : O(|str1|*|str2|)
Expected Auxiliary Space: O(|str1|*|str2|)
Constraints:
1<=size(str1),size(str2)<=103
0
2019sushilkumarkoriin 6 hours
int lcs(int x, int y, string s1, string s2)
    {
        // your code here
        int tb[x+1][y+1];
        for(int i=0;i<=x;i++){
            for(int j=0;j<=y;j++){
                if(i==0 || j==0){
                    tb[i][j] = 0;
                }
            }
        }
        for(int i=1;i<=x;i++){
            for(int j=1;j<=y;j++){
                char a = s1[i-1];
                char b = s2[j-1];
                if(a == b){
                    tb[i][j] = tb[i-1][j-1]+1;
                }
                else{
                    tb[i][j] = max(tb[i-1][j],tb[i][j-1]);
                }
            }
        }
        return tb[x][y];
    }
0
gargharshita624in 48 minutes
def lcs(self,x,y,s1,s2):              # code here       table=[[0 for _ in range(y+1)] for _ in range(x+1)]              for i in range(x):           for j in range(y):               if s1[i]==s2[j]:                   table[i+1][j+1]=1+table[i][j]               else:                   table[i+1][j+1]=max(table[i][j+1],table[i+1][j])       return table[-1][-1]
0
bhavyakawatra623 hours ago
O(N*N) - Dynamic Programming approach 

class Solution
{
    public:
    //Function to find the length of longest common subsequence in two strings.
    int lcs(int x, int y, string s1, string s2)
    {
        // dp[i][j] -> length of longest common subsequnce on taking string 1 till i-1 th indx and 
        // string 2 till j-1 th indx
        vector<vector<int>>dp(x+1,vector<int>(y+1,0));
        for(int i=1;i<=x;i++){
            for(int j=1;j<=y;j++){
                if(s1[i-1]==s2[j-1]){
                    dp[i][j]=dp[i-1][j-1]+1;
                }else{
                    dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
                }
            }
        }
        return dp[x][y];
    }
};
0
udhayashan11 day ago
#Clear recursive method
#User function Template for python3

class Solution:
    
    #Function to find the length of longest common subsequence in two strings.
    def lcs(self,x,y,str1,str2):
        
        # code here
        
        import sys
        dp = {}
        import functools
        @functools.lru_cache(None)
        def dfs(i,j):
            if i >= len(str1) or j >= len(str2):
                return 0
            
            if str1[i] == str2[j]:
                y1 = dfs(i+1,j+1)+1
                dp[(i,j)] = y1
            else:
                y1 = dfs(i+1,j)
                y2 = dfs(i,j+1)
                dp[(i,j)] = max(y1,y2)
            return dp[(i,j)]
        
        return(dfs(0,0))

#{ 
#  Driver Code Starts
#Initial Template for Python 3
import atexit
import io
import sys

# Contributed by : Nagendra Jha

if __name__ == '__main__':
    test_cases = int(input())
    for cases in range(test_cases):
        x,y = map(int,input().strip().split())
        s1 = str(input())
        s2 = str(input())
        ob=Solution()
        print(ob.lcs(x,y,s1,s2))
# } Driver Code Ends
0
subhashishde081 day ago
    int helper(string s1,string s2,int **dp){
        int m = s1.length();
        int n = s2.length();
        
        if(s1.length()==0 || s2.length()==0) return 0;
        
        if(dp[m][n]!=-1){
            return dp[m][n];
        }
        
        int ans;
        
        if(s1[0]==s2[0]){
            ans = 1+helper(s1.substr(1),s2.substr(1),dp);
        }
        else{
             int a = helper(s1.substr(1),s2,dp);
             int b = helper(s1,s2.substr(1),dp);
             
             ans = max(a,b);
        }
        return dp[m][n] = ans;
    }
    int lcs(int x, int y, string s1, string s2)
    {
        // your code here
        int **dp = new int*[x+1];
        for(int i=0;i<=x;i++){
            dp[i] = new int[y+1];
            for(int j=0;j<=y;j++){
                dp[i][j] = -1;
            }
        }
        return helper(s1,s2,dp);
        
    }
+5
mollang2 days ago
Time Complexity : O(x*y)
Space Complexity: O(min(x,y))
 
Optimized Iterative DP Approach:
    int lcs(int x, int y, string s1, string s2)
    {
        if(y>x){
            swap(x,y);
            swap(s1,s2);
        }
        int dp[2][y+1];
        for(int i=x; i>=0; i--){
            for(int j=y; j>=0; j--){
                if(i==x or j==y){
                    dp[i%2][j]=0;
                    continue;
                }
                if(s1[i]==s2[j])
                	dp[i%2][j]=1+dp[(i+1)%2][j+1];
                else
                 	dp[i%2][j]=max(dp[(i+1)%2][j],dp[i%2][j+1]);                
            }
        }
        return dp[0][0];
    }
0
kamresh4853 days ago
int lcs(int x, int y, string s1, string s2)
   {
       vector<vector<int>> memo(x+1,vector<int>(y+1,0));
       for(int i=0;i<x+1;i++)
           for(int j=0;j<y+1;j++)
               memo[i][j] = (i==0 || j==0) 
               ?0 
               :s1[i-1]==s2[j-1]
                   ?1+memo[i-1][j-1]
                   :max(memo[i-1][j],memo[i][j-1]);    
       return memo[x][y];
   }
0
pseudocoder6 days ago
// recursive solution (will not work gives TLE)
class Solution{   public:   int lcs(int n, int m, string s1, string s2)   {       if(n == 0 || m == 0)       {           return 0;       }       if(s1[n-1] == s2[m-1])           return 1+lcs(n-1,m-1,s1,s2);       else       {           return max(lcs(n,m-1,s1,s2),lcs(n-1,m,s1,s2));       }          }};
// Memoization code
class Solution{   public:   // static int t[1001][1001];   int solve(int n, int m, string s1, string s2,vector<vector<int>>&t)   {       if(n == 0 || m == 0)       {           return 0;       }       if(t[n][m]!=-1)       {           return t[n][m];       }       if(s1[n-1] == s2[m-1])       {          return t[n][m] = 1+solve(n-1,m-1,s1,s2,t);                  }       else       {           t[n][m] = max(solve(n,m-1,s1,s2,t),solve(n-1,m,s1,s2,t));           return t[n][m];       }   }   int lcs(int n, int m, string s1, string s2)   {       vector<vector<int>>t(n+1,vector<int>(m+1,-1));       int x = solve(n,m,s1,s2,t);       return x;   }};
 
// Top -Down approach 
 
class Solution{   public:      int lcs(int n, int m, string s1, string s2)   {       vector<vector<int>> t(n+1,vector<int>(m+1,0));              for(int i = 1; i < n+1; i++)       {           for(int j = 1; j < m+1; j++)           {               if(s1[i-1]==s2[j-1])               {                   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];   }}; 
 
 
+1
kunal220200311 week ago
Simple Tabulation Solution With C++
    public:
    //Function to find the length of longest common subsequence in two strings.
    int lcs(int x, int y, string s1, string s2)
    {
        vector<vector<int>> dp(x+1,vector<int>(y+1,0));
        
        for(int i = 1; i <= x; i++)
            for(int j = 1; j <= y; j++)
            {
                if(s1[i-1] == s2[j-1])
                    dp[i][j] =  1+ dp[i-1][j-1];
                else
                    dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
            }
        return dp[x][y];
    }
0
avinashdhn19041 week ago
class Solution
{
    public:
    //Function to find the length of longest common subsequence in two strings.
    int dp[1001][1001];
    int solve(int x,int y,string s1,string s2){
        if(x==0||y==0)return 0;
        if(dp[x][y]!=-1)return dp[x][y];
        if(s1[x-1]==s2[y-1])dp[x][y]=1+solve(x-1,y-1,s1,s2);
        else{
            dp[x][y]=max(solve(x-1,y,s1,s2),solve(x,y-1,s1,s2));
        }
        return dp[x][y];
    }
    int lcs(int x, int y, string s1, string s2)
    {
      memset(dp,-1,sizeof(dp));
        return solve(x,y,s1,s2);
    }
};
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.