2-D Dynamic Programming Two strings
569. Shortest Common Supersequence
You are given two strings, str1 and str2. Return the shortest string that has both of them as
subsequences.
A subsequence of a string is what is left after deleting some of its letters, or none, without changing
the order of the rest. "ace" is a subsequence of "abcde", but "eca" is not. A string that has both
str1 and str2 as subsequences is a common supersequence of the two.
Often several shortest answers exist, and any of them is correct. When the string you return is a common
supersequence of str1 and str2, the result shows its length, as a common supersequence of length 8.
Otherwise it shows which of the two strings is not a subsequence of it, and the first letter of that string
with no match. Positions count from 0.
Example 1
Input: str1 = "peach", str2 = "apple"
"appleach"Explanation: "apple" sits at indexes 0 to 4 of the answer, and "peach" at indexes 1, 4, 5, 6 and 7. The p and the e
serve both strings. No common supersequence has 7 letters.
Example 2
Input: str1 = "dog", str2 = "cat"
"catdog"Explanation: The strings share no letter, so the answer holds all six. Any order that keeps each string's letters in
order is correct, such as "dogcat" or "cdaotg".
Example 3
Input: str1 = "nan", str2 = "banana"
"banana"Explanation: "nan" is already a subsequence of "banana", at indexes 2, 3 and 4, so str2 itself is a shortest
answer.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ str1.length, str2.length ≤ 3000str1andstr2hold only lowercase English letters.
Clarifying questions
What you would ask an interviewer before writing any code.