Shortest Common Supersequence - Problem
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.
Input & Output
Example 1 — Basic Case
$
Input:
str1 = "ab", str2 = "ac"
›
Output:
"aacb"
💡 Note:
One possible supersequence is "aacb": 'a' appears in both strings, so we include it once, then 'a' from str2, then 'c' from str2, then 'b' from str1
Example 2 — No Common Characters
$
Input:
str1 = "abc", str2 = "def"
›
Output:
"abcdef"
💡 Note:
Since there are no common characters, we simply concatenate: "abc" + "def" = "abcdef"
Example 3 — Longer Common Subsequence
$
Input:
str1 = "abac", str2 = "cab"
›
Output:
"cabac"
💡 Note:
LCS is "ab", so we merge optimally: 'c' from str2, then common 'a', then common 'b', then remaining 'a', 'c' from str1
Constraints
- 1 ≤ str1.length, str2.length ≤ 1000
- str1 and str2 consist of lowercase English letters.
Visualization
Tap to expand
Understanding the Visualization
1
Input Strings
Two strings that need to be merged: str1="ab", str2="ac"
2
Find Common Parts
Identify longest common subsequence to avoid duplication
3
Build Supersequence
Merge optimally to create shortest result: "aacb"
Key Takeaway
🎯 Key Insight: Use LCS to identify common parts and include them only once in the final supersequence
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code