You are given two strings ‘s1’ and ‘s2’.
Return the longest common subsequence of these strings.
If there’s no such string, return an empty string. If there are multiple possible answers, return any such string.
Longest common subsequence of string ‘s1’ and ‘s2’ is the longest subsequence of ‘s1’ that is also a subsequence of ‘s2’. A ‘subsequence’ of ‘s1’ is a string that can be formed by deleting one or more (possibly zero) characters from ‘s1’.
Input: ‘s1’ = “abcab”, ‘s2’ = “cbab”
Output: “bab”
Explanation:
“bab” is one valid longest subsequence present in both strings ‘s1’ , ‘s2’.
The first line of input contains two integers ‘n’ and ‘m’, length of ‘s1’ and length of ‘s2’.
The second line of the input contains the string ‘s1’.
The third line of the input contains the string ‘s2’.
Return a string which is the longest common subsequence of ‘s1’ and ‘s2’. If there’s no such string return an empty string.
You don’t need to print anything, it has already been taken care of, just complete the given function. ‘1’ will be printed if the given subsequence is present in both the strings and length of the string is equal to the longest common subsequence and ‘0’ otherwise.
5 6
ababa
cbbcad
"bba"
1
“bba” is only possible longest subsequence present in both s1 = “ababa” and s2 = “cbbcad”. '1' is printed if the returned string is equal to "bba".
3 3
xyz
abc
""
1
There’s no subsequence of ‘s1’ that is also present in ‘s2’. Thus an empty string is returned and '1' is printed.
Try to solve this in O(n*m). Where ‘n’ is the length of ‘s1’ and ‘m’ is the length of ‘s2’.
1 <= n, m <= 10^3
Time Limit: 1 sec
Think about transitions used during calculating length of LCS using dynamic programming.
Approach:
We will first calculate the length of LCS using dynamic programming. While calculating LCS using dynamic programming we use the following transitions:
We will start from i = ‘n’, j = ‘m’ where ‘n’ is length of ‘s1’ and ‘m’ is length of ‘s2’ (we are taking indices to be ‘1’ indexed) .
We will keep repeating the above steps until both ‘i’ and ‘j’ are > 0. Then reverse the string we got from the above process, and we have our answer.
The steps are as follows:
function calculateLCS(int n, int m, string s1, string s2, vector<vector<int>> &dp)
function findLCS(int n, int m, string s1, string s2)
O(n*m), where ‘n’ is the length of ‘s1’ and ‘m’ is the length of ‘s2’.
While calculating values of dp array we are iterating via ‘i’ from 1 to ‘n’, and for each value of ‘i’ we are iterating from ‘1’ to ’m’ via ‘j’.
Hence, the time complexity is O(n*m).
O(n*m), where ‘n’ is the length of ‘s1’ and ‘m’ is the length of ‘s2’.
We are using a 2D array ‘dp’ of size n*m.
Hence, the space complexity is O(n*m).