![]() |
VOOZH | about |
Welcome to the daily solutions of our . We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Dynamic Programming but will also help you build up problem-solving skills.
Given two strings X and Y of lengths m and n respectively, find the length of the smallest string that has both, X and Y as its sub-sequences.
Note: X and Y can have both uppercase and lowercase letters.
Examples:
Input: X = "abcd", Y = "xycd"
Output: 6
Explanation: Shortest Common Supersequence would be abxycd which is of length 6 and has both the strings as its subsequences.Input: X = "efgh", Y = "jghi"
Output: 6
Explanation: Shortest Common Supersequence would be ejfghi which is of length 6 and has both the strings as its subsequences.
We need to find a string that has both strings as subsequences and is the shortest such string. If both strings have all characters different, then result is sum of lengths of two given strings. If there are common characters, then we don’t want them multiple times as the task is to minimize length. Therefore, we first find the longest common subsequence, take one occurrence of this subsequence and add extra characters.
Length of the shortest supersequence = (Sum of lengths of given two strings) - (Length of LCS of two given strings)
Below is the implementation of the above approach:
Time Complexity: O(|X| * |Y|), where |X| is the length of string X and |Y| is the length of string Y.
Auxiliary Space: O(|X| * |Y|)