10. Longest Common Subsequence
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
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
and s2
. For each character:
If they match, update dp[i][j]
as 1 + dp[i-1][j-1]
.
Otherwise, set it to the maximum of dp[i-1][j]
and dp[i][j-1]
.
The final value at dp[n][m]
will be the length of the longest common subsequence.
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 Complexity: O(n * m)
, where n
is the length of s1
and m
is the length of s2
.
Auxiliary Space Complexity: O(n * m)
, as we are using a 2D array dp
of size (n+1)*(m+1)
.
For discussions, questions, or doubts related to this solution, please visit our . 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 repository.