Shortest Common Supersequence

Implement shortestCommonSupersequence

Given two strings str1 and str2, find the shortest possible string that contains both of them as subsequences (characters in the right relative order, not necessarily adjacent). If several shortest strings work, any one of them is accepted. Whatever gets merged for free has to be a character both strings already agree on, in the same relative order — in other words, exactly the longest common subsequence. Everything outside that shared backbone still needs to appear once, taken verbatim from whichever original string it came from. So the shape of the answer falls out of the LCS length table almost immediately: walk that table from the end of both strings back to the start, and at every step either the two current characters already match (keep one copy, move past both) or they don't (copy whichever character still has more shared potential ahead of it, according to the table, and move past just that one side). What's left over once one string runs out gets tacked on unchanged.

Example 1:

Input: str1 = "abac", str2 = "cab"

Output: "cabac"

Example 2:

Input: str1 = "abc", str2 = "def"

Output: "defabc"

Example 3:

Input: str1 = "abc", str2 = "abc"

Output: "abc"

+ 7 hidden test cases run on Submit.

Constraints:

  • 0 ≤ str1.length, str2.length ≤ 10
  • str1 and str2 consist of lowercase English letters
  • the returned string's length never exceeds str1.length + str2.length

str1 =

abac

str2 =

cab