Given two strings, str1
and str2
, find the shortest string that contains both str1
and str2
as subsequences.
Definition: A string S is a subsequence of another string T if you can remove some characters from T (without changing the order of the remaining characters) to get S.
Input:
str1 = "abac"
str2 = "cab"
Output:
"cabac"
Explanation:
"abac"
is a subsequence of "cabac"
(for example, remove the first "c"
)."cab"
is also a subsequence of "cabac"
(for example, remove the last "ac"
).Input:
str1 = "aaaaaaaa"
str2 = "aaaaaaaa"
Output:
"aaaaaaaa"
Explanation:
Both strings are identical; therefore, the SCS is the same as each string.
Input:
str1 = "geek"
str2 = "eke"
Possible Output:
"geeke"
Explanation:
"geek"
is a subsequence of "geeke"
(remove the extra "e"
in the middle)."eke"
is also a subsequence of "geeke"
.Input:
str1 = "AGGTAB"
str2 = "GXTXAYB"
Possible Output:
"AGGXTXAYB"
Explanation:
The output "AGXGTXAYB"
is one valid SCS that contains both "AGGTAB"
and "GXTXAYB"
as subsequences.
len(str1) + len(str2) - len(LCS(str1, str2))
The DP array (or table) plays a crucial role in solving the Shortest Common Supersequence (SCS) problem by first helping us compute the Longest Common Subsequence (LCS) of the two input strings.
DP Array Construction:
dp
with dimensions (m+1) x (n+1)
, where m
and n
are the
lengths of the two strings.dp[i][j]
stores the length of the LCS between the first i
characters of str1
and the
first
j
characters of str2
.This is computed using the following rules:
str1[i-1] == str2[j-1]
, then dp[i][j] = dp[i-1][j-1] + 1
.dp[i][j] = max(dp[i-1][j], dp[i][j-1])
.Why LCS Matters:
len(SCS) = len(str1) + len(str2) - len(LCS)
shows that the more characters the strings share (in order), the shorter the SCS can be.Backtracking Using the DP Array:
dp[m][n]
to reconstruct the SCS.str1[i-1]
and str2[j-1]
are the same, that character is part of the LCS, so we include it in the SCS and move diagonally (i.e., i--, j--
).dp[i-1][j]
and dp[i][j-1]
:
The DP array is useful because it:
In essence, the DP array is the backbone of the solution—it not only provides the length of the LCS (which directly relates to the minimum SCS length) but also guides the process of merging the two strings into one minimal supersequence.
Feel free to use these examples to test and understand your solution!
https://leetcode.com/problems/shortest-common-supersequence/description/
Loading component...
Loading component...