Shortest Common Supersequence

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.

30:00

Shortest Common Supersequence
hard
Free written solution
Topics
Companies

Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If there are multiple valid strings, return any of them. A string s is a subsequence of string t if deleting some number of characters from t (possibly 0) results in the string s.

Example 1:
Input: {"str1":"abac","str2":"cab"}
Output: cabac
Constraints:
  • 1≤str1.length,str2.length≤10001 \leq \text{str1.length}, \text{str2.length} \leq 1000

  • str1 and str2 consist of lowercase English letters.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"str1":"abac","str2":"cab"}

First find the longest common subsequence (LCS). Letters in it can be written once and shared; every other letter must be written separately. dp[i][j] = LCS of the first i letters of str1 and the first j of str2.

str1

a
b
a
c

str2

c
a
b

LCS table

∅
c
a
b
∅
0
0
0
0
a
0
b
0
a
0
c
0

Supersequence (built right to left): 0 letters

(nothing written yet)

shared (LCS)

only from str1

only from str2

Variables
VariableValue
m4
n3
DepthFunction Call
Stack empty
0/19