
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.
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.