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
+1
kronizerdeltac4 days ago
JAVA TABULATION AND MEMOIZATION CODES:
 
1.MEMOIZATION:
 
static int lcs_memo(String s1, String s2, int n, int m, int[][] dp) {
        if(n == 0 || m == 0)
            return 0;
        if(dp[n][m] != -1)
            return dp[n][m];
            
        if(s1.charAt(n - 1) == s2.charAt(m - 1))
            return dp[n][m] = lcs_memo(s1, s2, n - 1, m - 1, dp) + 1;
        else
            return dp[n][m] = Math.max(lcs_memo(s1, s2, n - 1, m, dp), lcs_memo(s1, s2, n, m - 1, dp));
    }
    
    static int lcs(int x, int y, String s1, String s2)
    {
        int[][] dp = new int[x + 1][y + 1];
        for(int[] d : dp)
            Arrays.fill(d, - 1);
            
        return lcs_memo(s1, s2, x, y, dp);
    }
2. TABULATION:
 
static int lcs_tabu(String s1, String s2, int N, int M, int[][] dp) {
        for(int n = 0; n <= N; n++) {
            for(int m = 0; m <= M; m++) {
                if(n == 0 || m == 0) {
                    dp[n][m] = 0;
                    continue;
                }
                
                if(s1.charAt(n - 1) == s2.charAt(m - 1))
                    dp[n][m] = dp[n - 1][m - 1] + 1;
                else
                    dp[n][m] = Math.max(dp[n - 1][m], dp[n][m - 1]);
            }
        }
        return dp[N][M];
    }
    
    static int lcs(int x, int y, String s1, String s2)
    {
        int[][] dp = new int[x + 1][y + 1];
        for(int[] d : dp)
            Arrays.fill(d, - 1);
            
        return lcs_tabu(s1, s2, x, y, dp);
    }
+1
ayushkokande3324 days ago
 int lcs(int x, int y, string s, string p)
    {
        // your code here
       vector<vector<int>>dp(s.length()+1,vector<int>(p.length()+1,0));
        for(int i=1;i<=s.length();i++){
            for(int j=1;j<=p.length();j++){
                if(s[i-1]==p[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[s.length()][p.length()];
    }
+1
kashyapjhon5 days ago
C++ Solution MEDIUM
Method 1→ MEMOIZATION TIME=(0.05/1.72):
int help(vector<vector<int> > &dp, string s1,string s2,int n,int m){      if(n==0 || m==0){          return 0;      }      if(dp[n][m]!=-1){          return dp[n][m];      }      if(s1[n-1]==s2[m-1]){          return dp[n][m]=1+help(dp,s1,s2,n-1,m-1);      }      else{          return dp[n][m]=max(help(dp,s1,s2,n-1,m),help(dp,s1,s2,n,m-1));      }  }  int lcs(int x, int y, string s1, string s2)  {      // your code here      vector<vector<int> > dp(x+1,vector<int>(y+1,-1));      return help(dp,s1,s2,x,y);  }
Method 2→ TABULATION TIME=(0.01/1.72):
int lcs(int x, int y, string s1, string s2)  {      // your code here      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
shivamshuklashivam296 days ago
class Solution
{   
    int dp[1002][1002];
    public:
    Solution(){
        memset(dp , -1 , sizeof(dp));
    }
    //Function to find the length of longest common subsequence in two strings.
    int lcs(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]) return dp[x][y] =  1+ lcs(x-1,y-1,s1,s2);
        else  return dp[x][y] =  max(lcs(x-1,y,s1,s2) , lcs(x,y-1,s1,s2));
    }
};
0
annanyamathur2 weeks ago
int lcs(int x, int y, string s1, string s2)
    {
        int dp[x+1][y+1];
       memset(dp,0,sizeof(dp));
        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
aniketsaraswat1122 weeks ago
int lcs(int x, int y, string s1, string s2){
        int dp[x+1][y+1] = {};
        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-1],max(dp[i-1][j],dp[i][j-1]));
            }
        }
        return dp[x][y];
    }
0
yashvardhansingh20192 weeks ago
Java Short & Easy Time efficient Code
int[][] dp  = new int[x+1][y+1];       for(int i=1;i<=x;i++){           for(int j=1;j<=y;j++){               if(s1.charAt(i-1)==s2.charAt(j-1)){                   dp[i][j] =  1+ dp[i-1][j-1];               }else{                   dp[i][j] =  Math.max(dp[i-1][j],dp[i][j-1]);               }           }       }       return dp[x][y];
0
cshubham4392 weeks ago
if(i==s1.length() || j == s2.length()){
            return 0;
        }
        int myans;
        if(s1.charAt(i)==s2.charAt(j)){
            int smallans;
            if(arr[i+1][j+1]==-1){
                smallans = common(s1,s2,i+1,j+1,arr);
                arr[i+1][j+1] = smallans;
            }
            else{
                smallans = arr[i+1][j+1];
            }
            myans = 1+smallans;
            
        }
        else{
           int ans1,ans2;
           if(arr[i+1][j] == -1){
               ans1 = common(s1,s2,i+1,j,arr);
               arr[i+1][j] = ans1;
           }
           else{
               ans1 = arr[i+1][j];
           }
           if(arr[i][j+1]==-1){
               ans2 = common(s1,s2,i,j+1,arr);
               arr[i][j+1] = ans2;
           }
           else{
               ans2 = arr[i][j+1];
           }
           myans = Math.max(ans2,ans1);
        }
        return myans;
    }
    static int lcs(int x, int y, String s1, String s2)
    {
        int arr[][] = new int[x+1][y+1];
        for(int i = 0; i<x;i++){
            for(int j = 0;j<y;j++){
                arr[i][j] = -1;
            }
        }
        int ans  = common(s1,s2,0,0,arr);
        return ans;
       
0
amarrajsmart1971 month ago
 int lcs(int x, int y, string s1, string s2)   {       // your code here              int dp[s1.length()+1][s2.length()+1];              for(int x=0;x<=s1.length();x++)       {           for(int y=0;y<=s2.length();y++)           {               if(x==0||y==0)               dp[x][y]=0;                              else if(s1[x-1]==s2[y-1])               {                   dp[x][y]=1+dp[x-1][y-1];               }                              else               {                   dp[x][y]=max(dp[x][y-1],dp[x-1][y]);               }           }       }       return dp[s1.length()][s2.length()];   }
 
0
ashishsharma4979
This comment was deleted.
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.