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
dpof 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
dpwith zeros since they represent the base case: the longest common subsequence with an empty string is zero.Iterate through the strings
s1ands2. 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:
s1 = "AGGTAB"
s2 = "GXTXAYB"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.
0 0 0 0 0 0 0
0 0 1 1 1 1 1
0 1 1 1 1 2 2
0 1 1 1 1 2 2
0 1 1 2 2 2 2
0 1 1 2 2 3 3The 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), wherenis the length ofs1andmis the length ofs2.Auxiliary Space Complexity:
O(n * m), as we are using a 2D arraydpof 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
Was this helpful?