10. Longest Common Subsequence
The problem can be found at the following link: Question Link
My Approach
This is a standard dynamic programming problem. To solve it, I follow these logic:
Initialize a 2D array
dp
of size(n+1) * (m+1)
to store the lengths of the longest common subsequences of substrings at each instance.Initialize the first row and the first column of
dp
with zeros since they represent the base case: the longest common subsequence with an empty string is zero.Iterate through the strings
s1
ands2
. For each character:If they match, update
dp[i][j]
as1 + dp[i-1][j-1]
.Otherwise, set it to the maximum of
dp[i-1][j]
anddp[i][j-1]
.
The final value at
dp[n][m]
will be the length of the longest common subsequence.
Explanation with Example
Consider the strings:
Using the dynamic programming approach, the dp
table would look like this, where the value of dp[i][j]
represents the longest subsequence found at that instance.
The final value at dp[6][7]
is 3
, which is the length of the longest common subsequence.
Time and Auxiliary Space Complexity
Time Complexity:
O(n * m)
, wheren
is the length ofs1
andm
is the length ofs2
.Auxiliary Space Complexity:
O(n * m)
, as we are using a 2D arraydp
of size(n+1)*(m+1)
.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated