oneby7

2-D Dynamic Programming Two strings

569. Shortest Common Supersequence

Hard

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"

Output: "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"

Output: "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"

Output: "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.

str1 = "cobra", str2 = "robot"

Constraints

  • 1 ≤ str1.length, str2.length ≤ 3000
  • str1 and str2 hold only lowercase English letters.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.