Given two strings, S1 and S2, the task is to find the length of the Longest Common Subsequence, i.e. longest subsequence present in both of the strings.
A longest common subsequence (LCS) is defined as the longest subsequence which is common in all given input sequences.
Longest Common Subsequence
Examples:
Input: S1 = “ABC”, S2 = “ACD” Output: 2 Explanation: The longest subsequence which is present in both strings is “AC”.
Input: S1 = “AGGTAB”, S2 = “GXTXAYB” Output: 4 Explanation: The longest common subsequence is “GTAB”.
Input: S1 = “ABC”, S2 = “CBA” Output: 1 Explanation: There are three common subsequences of length 1, “A”, “B” and “C” and no common subsequence.of length more than 1.
Input: S1 = “XYZW”, S2 = “XYWZ” Output: 3 Explanation: There are two common subsequences of length 3 “XYZ”, and”XYW”, and no common subsequence. of length more than 3.
Generate all the possible subsequences and find the longest among them that is present in both strings using recursion.
Follow the below steps to implement the idea:
Create a recursive function [say lcs()].
Check the relation between the First characters of the strings that are not yet processed.
Depending on the relation call the next recursive function as mentioned above.
Return the length of the LCS received as the answer.
Below is the implementation of the recursive approach:
C++
// A Naive recursive implementation of LCS problem#include<bits/stdc++.h>usingnamespacestd;// Returns length of LCS for X[0..m-1], Y[0..n-1]intlcs(stringX,stringY,intm,intn){if(m==0||n==0)return0;if(X[m-1]==Y[n-1])return1+lcs(X,Y,m-1,n-1);elsereturnmax(lcs(X,Y,m,n-1),lcs(X,Y,m-1,n));}// Driver codeintmain(){stringS1="AGGTAB";stringS2="GXTXAYB";intm=S1.size();intn=S2.size();cout<<"Length of LCS is "<<lcs(S1,S2,m,n);return0;}// This code is contributed by rathbhupendra
C
// A Naive recursive implementation// of LCS problem#include<stdio.h>intmax(inta,intb);// Returns length of LCS for X[0..m-1],// Y[0..n-1]intlcs(char*X,char*Y,inti,intj){if(X[i]==0||Y[j]==0)return0;if(X[i]==Y[j])return1+lcs(X,Y,i+1,j+1);elsereturnmax(lcs(X,Y,i,j+1),lcs(X,Y,i+1,j));}// Utility function to get max of// 2 integersintmax(inta,intb){return(a>b)?a:b;}// Driver codeintmain(){charS1[]="BD";charS2[]="ABCD";intm=strlen(S1);intn=strlen(S2);inti=0,j=0;// Function Callprintf("Length of LCS is %d",lcs(S1,S2,i,j));return0;}
Java
// A Naive recursive implementation of LCS problem in javaimportjava.io.*;importjava.util.*;publicclassLongestCommonSubsequence{// Returns length of LCS for X[0..m-1], Y[0..n-1]intlcs(StringX,StringY,intm,intn){if(m==0||n==0)return0;if(X.charAt(m-1)==Y.charAt(n-1))return1+lcs(X,Y,m-1,n-1);elsereturnmax(lcs(X,Y,m,n-1),lcs(X,Y,m-1,n));}// Utility function to get max of 2 integersintmax(inta,intb){return(a>b)?a:b;}// Driver codepublicstaticvoidmain(String[]args){LongestCommonSubsequencelcs=newLongestCommonSubsequence();StringS1="AGGTAB";StringS2="GXTXAYB";intm=S1.length();intn=S2.length();System.out.println("Length of LCS is"+" "+lcs.lcs(S1,S2,m,n));}}// This Code is Contributed by Saket Kumar
Python
# A Naive recursive Python implementation of LCS problemdeflcs(X,Y,m,n):ifm==0orn==0:return0elifX[m-1]==Y[n-1]:return1+lcs(X,Y,m-1,n-1)else:returnmax(lcs(X,Y,m,n-1),lcs(X,Y,m-1,n))# Driver codeif__name__=='__main__':S1="AGGTAB"S2="GXTXAYB"print("Length of LCS is",lcs(S1,S2,len(S1),len(S2)))
C#
// C# Naive recursive implementation of LCS problemusingSystem;classGFG{// Returns length of LCS for X[0..m-1], Y[0..n-1]staticintlcs(StringX,StringY,intm,intn){if(m==0||n==0)return0;if(X[m-1]==Y[n-1])return1+lcs(X,Y,m-1,n-1);elsereturnmax(lcs(X,Y,m,n-1),lcs(X,Y,m-1,n));}// Utility function to get max of 2 integersstaticintmax(inta,intb){return(a>b)?a:b;}// Driver codepublicstaticvoidMain(){StringS1="AGGTAB";StringS2="GXTXAYB";intm=S1.Length;intn=S2.Length;Console.Write("Length of LCS is"+" "+lcs(S1,S2,m,n));}}// This code is Contributed by Sam007
Javascript
<script>// A Naive recursive implementation of LCS problem in java// Returns length of LCS for X[0..m-1], Y[0..n-1]functionlcs(X,Y,m,n){if(m==0||n==0)return0;if(X[m-1]==Y[n-1])return1+lcs(X,Y,m-1,n-1);elsereturnmax(lcs(X,Y,m,n-1),lcs(X,Y,m-1,n));}// Utility function to get max of 2 integersfunctionmax(a,b){return(a>b)?a:b;}vars1="AGGTAB";vars2="GXTXAYB";varX=s1;varY=s2;varm=X.length;varn=Y.length;document.write("Length of LCS is"+" "+lcs(X,Y,m,n));// This code contributed by umadevi9616 </script>
PHP
<?php// A Naive recursive PHP // implementation of LCS problem functionlcs($X,$Y,$m,$n){if($m==0||$n==0)return0;elseif($X[$m-1]==$Y[$n-1])return1+lcs($X,$Y,$m-1,$n-1);elsereturnmax(lcs($X,$Y,$m,$n-1),lcs($X,$Y,$m-1,$n));}// Driver Code $S1="AGGTAB";$S2="GXTXAYB";echo"Length of LCS is ";echolcs($S1,$S2,strlen($S1),strlen($S2));// This code is contributed // by Shivi_Aggarwal ?>
Output
Length of LCS is 4
Time Complexity: O(2m+n) Auxiliary Space: O(1)
Longest Common Subsequence (LCS) using Memoization:
If we notice carefully, we can observe that the above recursive solution holds the following two properties:
1. Optimal Substructure:
See for solving the structure of L(X[0, 1, . . ., m-1], Y[0, 1, . . . , n-1]) we are taking the help of the substructures of X[0, 1, …, m-2], Y[0, 1,…, n-2], depending on the situation (i.e., using them optimally) to find the solution of the whole.
2. Overlapping Subproblems:
If we use the above recursive approach for strings “BD” and “ABCD“, we will get a partial recursion tree as shown below. Here we can see that the subproblem L(“BD”, “ABCD”) is being calculated more than once. If the total tree is considered there will be several such overlapping subproblems.
Approach: Because of the presence of these two properties we can use Dynamic programming or Memoization to solve the problem. Below is the approach for the solution using recursion.
Create a recursive function. Also create a 2D array to store the result of a unique state.
During the recursion call, if the same state is called more than once, then we can directly return the answer stored for that state instead of calculating again.
Below is the implementation of the above approach:
C++
// A Top-Down DP implementation// of LCS problem#include<bits/stdc++.h>usingnamespacestd;// Returns length of LCS for X[0..m-1],// Y[0..n-1]intlcs(char*X,char*Y,intm,intn,vector<vector<int>>&dp){if(m==0||n==0)return0;if(X[m-1]==Y[n-1])returndp[m][n]=1+lcs(X,Y,m-1,n-1,dp);if(dp[m][n]!=-1){returndp[m][n];}returndp[m][n]=max(lcs(X,Y,m,n-1,dp),lcs(X,Y,m-1,n,dp));}// Driver codeintmain(){charX[]="AGGTAB";charY[]="GXTXAYB";intm=strlen(X);intn=strlen(Y);vector<vector<int>>dp(m+1,vector<int>(n+1,-1));cout<<"Length of LCS is "<<lcs(X,Y,m,n,dp);return0;}
Java
/*package whatever //do not write package name here */importjava.io.*;classGFG{// A Top-Down DP implementation of LCS problem// Returns length of LCS for X[0..m-1], Y[0..n-1]staticintlcs(StringX,StringY,intm,intn,int[][]dp){if(m==0||n==0)return0;if(dp[m][n]!=-1)returndp[m][n];if(X.charAt(m-1)==Y.charAt(n-1)){dp[m][n]=1+lcs(X,Y,m-1,n-1,dp);returndp[m][n];}dp[m][n]=Math.max(lcs(X,Y,m,n-1,dp),lcs(X,Y,m-1,n,dp));returndp[m][n];}// Drivers codepublicstaticvoidmain(Stringargs[]){StringX="AGGTAB";StringY="GXTXAYB";intm=X.length();intn=Y.length();int[][]dp=newint[m+1][n+1];for(inti=0;i<m+1;i++){for(intj=0;j<n+1;j++){dp[i][j]=-1;}}System.out.println("Length of LCS is "+lcs(X,Y,m,n,dp));}}// This code is contributed by shinjanpatra
Python
# A Top-Down DP implementation of LCS problem# Returns length of LCS for X[0..m-1], Y[0..n-1]deflcs(X,Y,m,n,dp):if(m==0orn==0):return0if(dp[m][n]!=-1):returndp[m][n]ifX[m-1]==Y[n-1]:dp[m][n]=1+lcs(X,Y,m-1,n-1,dp)returndp[m][n]dp[m][n]=max(lcs(X,Y,m,n-1,dp),lcs(X,Y,m-1,n,dp))returndp[m][n]# Driver codeX="AGGTAB"Y="GXTXAYB"m=len(X)n=len(Y)dp=[[-1foriinrange(n+1)]forjinrange(m+1)]print(f"Length of LCS is {lcs(X,Y,m,n,dp)}")# This code is contributed by shinjanpatra
C#
/* C# Naive recursive implementation of LCS problem */usingSystem;classGFG{/* Returns length of LCS for X[0..m-1], Y[0..n-1] */staticintlcs(char[]X,char[]Y,intm,intn,int[,]L){if(m==0||n==0)return0;if(L[m,n]!=-1)returnL[m,n];if(X[m-1]==Y[n-1]){L[m,n]=1+lcs(X,Y,m-1,n-1,L);returnL[m,n];}L[m,n]=max(lcs(X,Y,m,n-1,L),lcs(X,Y,m-1,n,L));returnL[m,n];}/* Utility function to get max of 2 integers */staticintmax(inta,intb){return(a>b)?a:b;}publicstaticvoidMain(){Strings1="AGGTAB";Strings2="GXTXAYB";char[]X=s1.ToCharArray();char[]Y=s2.ToCharArray();intm=X.Length;intn=Y.Length;int[,]L=newint[m+1,n+1];for(inti=0;i<=m;i++){for(intj=0;j<=n;j++){L[i,j]=-1;}}Console.Write("Length of LCS is"+" "+lcs(X,Y,m,n,L));}}// This code is contributed by akshitsaxenaa09
Javascript
/* A Top-Down DP implementation of LCS problem *//* Returns length of LCS for X[0..m-1], Y[0..n-1] */functionlcs(X,Y,m,n,dp){if(m==0||n==0)return0;if(X[m-1]==Y[n-1])returndp[m][n]=1+lcs(X,Y,m-1,n-1,dp);if(dp[m][n]!=-1){returndp[m][n];}returndp[m][n]=Math.max(lcs(X,Y,m,n-1,dp),lcs(X,Y,m-1,n,dp));}/* Driver code */letX="AGGTAB";letY="GXTXAYB";letm=X.length;letn=Y.length;letdp=newArray(m+1);for(leti=0;i<m+1;i++){dp[i]=newArray(n+1).fill(-1);}console.log("Length of LCS is "+lcs(X,Y,m,n,dp));// This code is contributed by shinjanpatra
Output
Length of LCS is 4
Time Complexity: O(m * n) where m and n are the string lengths. Auxiliary Space: O(m * n) Here the recursive stack space is ignored.
Longest Common Subsequence (LCS) using Bottom-Up (Tabulation):
We can use the following steps to implement the dynamic programming approach for LCS.
Create a 2D array dp[][] with rows and columns equal to the length of each input string plus 1 [the number of rows indicates the indices of S1 and the columns indicate the indices of S2].
Initialize the first row and column of the dp array to 0.
Iterate through the rows of the dp array, starting from 1 (say using iterator i).
For each i, iterate all the columns from j = 1 to n:
If S1[i-1] is equal to S2[j-1], set the current element of the dp array to the value of the element to (dp[i-1][j-1] + 1).
Else, set the current element of the dp array to the maximum value of dp[i-1][j] and dp[i][j-1].
After the nested loops, the last element of the dp array will contain the length of the LCS.
See the below illustration for a better understanding:
Illustration:
Say the strings are S1 = “AGGTAB” and S2 = “GXTXAYB”.
First step: Initially create a 2D matrix (say dp[][]) of size 8 x 7 whose first row and first column are filled with 0.
Creating the dp table
Second step: Traverse for i = 1. When j becomes 5, S1[0] and S2[4] are equal. So the dp[][] is updated. For the other elements take the maximum of dp[i-1][j] and dp[i][j-1]. (In this case, if both values are equal, we have used arrows to the previous rows).
Filling the row no 1
Third step: While traversed for i = 2, S1[1] and S2[0] are the same (both are ‘G’). So the dp value in that cell is updated. Rest of the elements are updated as per the conditions.
Filling the row no. 2
Fourth step: For i = 3, S1[2] and S2[0] are again same. The updations are as follows.
Filling row no. 3
Fifth step: For i = 4, we can see that S1[3] and S2[2] are same. So dp[4][3] updated as dp[3][2] + 1 = 2.
Filling row 4
Sixth step: Here we can see that for i = 5 and j = 5 the values of S1[4] and S2[4] are same (i.e., both are ‘A’). So dp[5][5] is updated accordingly and becomes 3.
Filling row 5
Final step: For i = 6, see the last characters of both strings are same (they are ‘B’). Therefore the value of dp[6][7] becomes 4.
Filling the final row
So we get the maximum length of common subsequence as 4.
Following is a tabulated implementation for the LCS problem.
C++
// Dynamic Programming C++ implementation// of LCS problem#include<bits/stdc++.h>usingnamespacestd;// Returns length of LCS for X[0..m-1],// Y[0..n-1]intlcs(stringX,stringY,intm,intn){// Initializing a matrix of size// (m+1)*(n+1)intL[m+1][n+1];// Following steps build L[m+1][n+1]// in bottom up fashion. Note that// L[i][j] contains length of LCS of// X[0..i-1] and Y[0..j-1]for(inti=0;i<=m;i++){for(intj=0;j<=n;j++){if(i==0||j==0)L[i][j]=0;elseif(X[i-1]==Y[j-1])L[i][j]=L[i-1][j-1]+1;elseL[i][j]=max(L[i-1][j],L[i][j-1]);}}// L[m][n] contains length of LCS// for X[0..n-1] and Y[0..m-1]returnL[m][n];}// Driver codeintmain(){stringS1="AGGTAB";stringS2="GXTXAYB";intm=S1.size();intn=S2.size();// Function callcout<<"Length of LCS is "<<lcs(S1,S2,m,n);return0;}
Java
// Dynamic Programming Java implementation of LCS problemimportjava.util.*;publicclassLongestCommonSubsequence{// Returns length of LCS for X[0..m-1], Y[0..n-1]intlcs(StringX,StringY,intm,intn){intL[][]=newint[m+1][n+1];// Following steps build L[m+1][n+1] in bottom up// fashion. Note that L[i][j] contains length of LCS// of X[0..i-1] and Y[0..j-1]for(inti=0;i<=m;i++){for(intj=0;j<=n;j++){if(i==0||j==0)L[i][j]=0;elseif(X.charAt(i-1)==Y.charAt(j-1))L[i][j]=L[i-1][j-1]+1;elseL[i][j]=max(L[i-1][j],L[i][j-1]);}}returnL[m][n];}// Utility function to get max of 2 integersintmax(inta,intb){return(a>b)?a:b;}publicstaticvoidmain(String[]args){LongestCommonSubsequencelcs=newLongestCommonSubsequence();StringS1="AGGTAB";StringS2="GXTXAYB";intm=S1.length();intn=S2.length();System.out.println("Length of LCS is"+" "+lcs.lcs(S1,S2,m,n));}}// This Code is Contributed by Saket Kumar
Python
# Dynamic Programming implementation of LCS problemdeflcs(X,Y,m,n):# Declaring the array for storing the dp valuesL=[[None]*(n+1)foriinrange(m+1)]# Following steps build L[m+1][n+1] in bottom up fashion# Note: L[i][j] contains length of LCS of X[0..i-1]# and Y[0..j-1]foriinrange(m+1):forjinrange(n+1):ifi==0orj==0:L[i][j]=0elifX[i-1]==Y[j-1]:L[i][j]=L[i-1][j-1]+1else:L[i][j]=max(L[i-1][j],L[i][j-1])# L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]returnL[m][n]# Driver codeif__name__=='__main__':S1="AGGTAB"S2="GXTXAYB"m=len(S1)n=len(S2)print("Length of LCS is",lcs(S1,S2,m,n))# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// Dynamic Programming implementation of LCS problemusingSystem;classGFG{// Returns length of LCS for X[0..m-1], Y[0..n-1]staticintlcs(StringX,StringY,intm,intn){int[,]L=newint[m+1,n+1];// Following steps build L[m+1][n+1]// in bottom up fashion.// Note that L[i][j] contains length of// LCS of X[0..i-1] and Y[0..j-1]for(inti=0;i<=m;i++){for(intj=0;j<=n;j++){if(i==0||j==0)L[i,j]=0;elseif(X[i-1]==Y[j-1])L[i,j]=L[i-1,j-1]+1;elseL[i,j]=max(L[i-1,j],L[i,j-1]);}}returnL[m,n];}// Utility function to get max of 2 integersstaticintmax(inta,intb){return(a>b)?a:b;}// Driver codepublicstaticvoidMain(){StringS1="AGGTAB";StringS2="GXTXAYB";intm=S1.Length;intn=S2.Length;Console.Write("Length of LCS is"+" "+lcs(S1,S2,m,n));}}// This Code is Contributed by Sam007
Javascript
// Dynamic Programming Java implementation of LCS problem// Utility function to get max of 2 integers functionmax(a,b){if(a>b)returna;elsereturnb;}// Returns length of LCS for X[0..m-1], Y[0..n-1] functionlcs(X,Y,m,n){varL=newArray(m+1);for(vari=0;i<L.length;i++){L[i]=newArray(n+1);}vari,j;/* Following steps build L[m+1][n+1] in bottom up fashion. Note that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */for(i=0;i<=m;i++){for(j=0;j<=n;j++){if(i==0||j==0)L[i][j]=0;elseif(X[i-1]==Y[j-1])L[i][j]=L[i-1][j-1]+1;elseL[i][j]=max(L[i-1][j],L[i][j-1]);}}/* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */returnL[m][n];}// Driver codevarS1="AGGTAB";varS2="GXTXAYB";varm=S1.length;varn=S2.length;console.log("Length of LCS is "+lcs(S1,S2,m,n));// This code is contributed by akshitsaxenaa09
PHP
<?php// Dynamic Programming C# // implementation of LCS problem functionlcs($X,$Y,$m,$n){// Following steps build L[m+1][n+1] // in bottom up fashion . // Note: L[i][j] contains length of // LCS of X[0..i-1] and Y[0..j-1]for($i=0;$i<=$m;$i++){for($j=0;$j<=$n;$j++){if($i==0||$j==0)$L[$i][$j]=0;elseif($X[$i-1]==$Y[$j-1])$L[$i][$j]=$L[$i-1][$j-1]+1;else$L[$i][$j]=max($L[$i-1][$j],$L[$i][$j-1]);}}// L[m][n] contains the length of // LCS of X[0..n-1] & Y[0..m-1] return$L[$m][$n];}// Driver Code $S1="AGGTAB";$S2="GXTXAYB";$m=strlen($S1);$n=strlen($S2);echo"Length of LCS is ";echolcs($S1,$S2,$m,$n);// This code is contributed // by Shivi_Aggarwal ?>
Output
Length of LCS is 4
Time Complexity: O(m * n) which is much better than the worst-case time complexity of Naive Recursive implementation. Auxiliary Space: O(m * n) because the algorithm uses an array of size (m+1)*(n+1) to store the length of the common substrings.
Longest Common Subsequence (LCS) using Bottom-Up (Space-Optimization):
In the above tabulation approach we are using L[i-1][j] and L[i][j] etc, here the L[i-1] will refers to the matrix L’s previous row and L[i] refers to the current row.
We can do space optimization by using two vectors one is previous and another one is current.
When the inner for loop exits we are initializing previous equal to current.
Below is the implementation:
C++
// Dynamic Programming C++ implementation// of LCS problem#include<bits/stdc++.h>usingnamespacestd;intlongestCommonSubsequence(string&text1,string&text2){intn=text1.size();intm=text2.size();// initializing 2 vectors of size mvector<int>prev(m+1,0),cur(m+1,0);for(intidx2=0;idx2<m+1;idx2++)cur[idx2]=0;for(intidx1=1;idx1<n+1;idx1++){for(intidx2=1;idx2<m+1;idx2++){// if matchingif(text1[idx1-1]==text2[idx2-1])cur[idx2]=1+prev[idx2-1];// not matchingelsecur[idx2]=0+max(cur[idx2-1],prev[idx2]);}prev=cur;}returncur[m];}intmain(){stringS1="AGGTAB";stringS2="GXTXAYB";// Function callcout<<"Length of LCS is "<<longestCommonSubsequence(S1,S2);return0;}
Java
// Dynamic Programming Java implementation of LCS problemimportjava.util.Arrays;publicclassGFG{publicstaticintlongestCommonSubsequence(Stringtext1,Stringtext2){intn=text1.length();intm=text2.length();// Initializing 2 arrays of size mint[]prev=newint[m+1];int[]cur=newint[m+1];for(intidx1=1;idx1<n+1;idx1++){for(intidx2=1;idx2<m+1;idx2++){// If matchingif(text1.charAt(idx1-1)==text2.charAt(idx2-1))cur[idx2]=1+prev[idx2-1];// Not matchingelsecur[idx2]=Math.max(cur[idx2-1],prev[idx2]);}prev=Arrays.copyOf(cur,m+1);}returncur[m];}publicstaticvoidmain(String[]args){StringS1="AGGTAB";StringS2="GXTXAYB";// Function callSystem.out.println("Length of LCS is "+longestCommonSubsequence(S1,S2));}}
Python
deflongestCommonSubsequence(text1,text2):n=len(text1)m=len(text2)# Initializing two lists of size mprev=[0]*(m+1)cur=[0]*(m+1)foridx1inrange(1,n+1):foridx2inrange(1,m+1):# If characters are matchingiftext1[idx1-1]==text2[idx2-1]:cur[idx2]=1+prev[idx2-1]else:# If characters are not matchingcur[idx2]=max(cur[idx2-1],prev[idx2])prev=cur.copy()returncur[m]if__name__=='__main__':S1="AGGTAB"S2="GXTXAYB"# Function callprint("Length of LCS is",longestCommonSubsequence(S1,S2))# This code is contributed by Rishabh Mathur
C#
usingSystem;classProgram{staticintLongestCommonSubsequence(stringtext1,stringtext2){intn=text1.Length;intm=text2.Length;// initializing 2 arrays of size mint[]prev=newint[m+1];int[]cur=newint[m+1];for(intidx2=0;idx2<m+1;idx2++)cur[idx2]=0;for(intidx1=1;idx1<n+1;idx1++){for(intidx2=1;idx2<m+1;idx2++){// if matchingif(text1[idx1-1]==text2[idx2-1])cur[idx2]=1+prev[idx2-1];// not matchingelsecur[idx2]=0+Math.Max(cur[idx2-1],prev[idx2]);}prev=cur;}returncur[m];}staticvoidMain(){stringS1="AGGTAB";stringS2="GXTXAYB";// Function callConsole.WriteLine("Length of LCS is "+LongestCommonSubsequence(S1,S2));}}
Javascript
functionlongestCommonSubsequence(text1,text2){constn=text1.length;constm=text2.length;// Initializing two arrays of size mletprev=newArray(m+1).fill(0);letcur=newArray(m+1).fill(0);for(letidx2=0;idx2<m+1;idx2++){cur[idx2]=0;}for(letidx1=1;idx1<n+1;idx1++){for(letidx2=1;idx2<m+1;idx2++){// If characters matchif(text1[idx1-1]===text2[idx2-1]){cur[idx2]=1+prev[idx2-1];}// If characters don't matchelse{cur[idx2]=Math.max(cur[idx2-1],prev[idx2]);}}// Update the 'prev' arrayprev=[...cur];}returncur[m];}// Main functionfunctionmain(){constS1="AGGTAB";constS2="GXTXAYB";// Function callconsole.log("Length of LCS is "+longestCommonSubsequence(S1,S2));}// Call the main functionmain();
Output
Length of LCS is 4
Time Complexity: O(m * n), which remains the same. Auxiliary Space: O(m) because the algorithm uses two arrays of size m.
Contact Us