Shortest Common Supersequence - Problem

You're given two strings str1 and str2, and your task is to find the shortest possible string that contains both strings as subsequences.

A subsequence is formed by deleting some (possibly zero) characters from a string while maintaining the relative order of the remaining characters. For example, "ace" is a subsequence of "abcde".

The shortest common supersequence is the smallest string that has both input strings as subsequences. Think of it as merging two strings optimally while preserving their character order.

Example: For strings "abac" and "cab", one possible shortest common supersequence is "cabac" (length 5), which contains both "abac" and "cab" as subsequences.

Goal: Return any valid shortest common supersequence. If multiple solutions exist with the same minimum length, any of them is acceptable.

Input & Output

example_1.py โ€” Basic Example
$ Input: {"str1": "abac", "str2": "cab"}
โ€บ Output: "cabac"
๐Ÿ’ก Note: Both 'abac' and 'cab' are subsequences of 'cabac'. The LCS is 'ca' with length 2, so minimum supersequence length is 4+3-2=5.
example_2.py โ€” No Common Characters
$ Input: {"str1": "abc", "str2": "def"}
โ€บ Output: "abcdef"
๐Ÿ’ก Note: Since strings share no common characters, we simply concatenate them. LCS length is 0, so result length is 3+3-0=6.
example_3.py โ€” One String is Subsequence
$ Input: {"str1": "abc", "str2": "aec"}
โ€บ Output: "aebac"
๐Ÿ’ก Note: The strings share common subsequence 'ac'. We merge optimally to get minimum length supersequence of length 3+3-2=4.

Constraints

  • 1 โ‰ค str1.length, str2.length โ‰ค 1000
  • str1 and str2 consist of lowercase English letters only
  • Important: Multiple valid answers may exist - return any shortest one

Visualization

Tap to expand
Shortest Common Supersequence VisualizationReading List 1"abac"abacOrder must be preserved!Reading List 2"cab"cabOrder must be preserved!Master List"cabac"cabacโœ“ Contains both subsequencesLength: 5 (optimal!)๐ŸŽฏ Key Insight:Optimal length = len(str1) + len(str2) - len(LCS) = 4 + 3 - 2 = 5โœจ Magic:Use DP to find LCS, then backtrack to build the supersequence!
Understanding the Visualization
1
Analyze Overlaps
Find books that appear in both lists (like finding LCS)
2
Smart Merging
When books overlap, include them once; otherwise include from both lists
3
Optimal Result
The final master list contains all books with minimal duplication
Key Takeaway
๐ŸŽฏ Key Insight: The shortest supersequence has length len(str1) + len(str2) - len(LCS), achieved by using dynamic programming to optimally merge the strings.
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
67.3K Views
Medium Frequency
~25 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen