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
Shortest Common Supersequence INPUT str1 = "ab" a b str2 = "ac" a c Goal: Find shortest string containing both as subsequences Common: 'a' Unique: 'b' from str1 Unique: 'c' from str2 ALGORITHM STEPS 1 Build LCS DP Table Find longest common subseq 0 a c a 1 1 b 1 1 2 Trace Back from End Start at dp[m][n] 3 Build Result String If chars match: add once Else: add from larger dp 4 Add Remaining Chars Append leftover from str1 and str2 SCS = m + n - LCS = 2 + 2 - 1 = 3 FINAL RESULT Shortest Common Supersequence: a a c b "aacb" Verification: str1 "ab" in "aacb": a_c_b --> a__b [OK] str2 "ac" in "aacb": aacb --> a_c_ [OK] Length = 4 (Optimal!) Key Insight: The SCS length formula is: len(str1) + len(str2) - len(LCS). By finding the Longest Common Subsequence first, we can build the SCS by merging both strings while including common characters only once. This DP approach runs in O(m*n) time and space complexity. TutorialsPoint - Shortest Common Supersequence | Optimal DP Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
89.0K 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