AlgoInsight

DSA problem

Shortest Common Supersequence

HardString DPPattern: String DPtop600GoogleAmazonMicrosoftBloombergAdobe

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.

The length of the shortest common supersequence (SCS) follows a clean identity: |SCS| = |str1| + |str2| - |LCS(str1, str2)|. Every character outside the LCS contributes one symbol; matches in the LCS are shared between both strings and contribute only one symbol total.

To reconstruct the SCS string itself, first build the LCS DP table dp[i][j] = LCS length of str1[0..i) and str2[0..j). Then walk backwards from dp[m][n] and reconstruct the supersequence character by character:

When one index reaches 0, prepend the remainder of the other string. Time and space are both O(m * n).

Examples

Example 1
Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation: "cabac" contains "abac" (positions 1, 2, 3, 4) and "cab" (positions 0, 1, 2) as subsequences. Its length 5 equals 4 + 3 - 2 where LCS("abac", "cab") = "ab".
Example 2
Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa"
Output: "aaaaaaaa"
Explanation: Identical strings share themselves as the LCS, so the SCS is also that same string.
Example 3
Input: str1 = "abc", str2 = "def"
Output: "abcdef"
Explanation: No characters are shared (LCS length 0). The SCS concatenates the two strings, giving length 6.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

stringdynamic-programminglcs

Browse all DSA problems