Shortest Common Supersequence Problem
Description
LeetCode Problem 1092.
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.
Example 1:
Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation:
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.
Example 2:
Input: str1 = "aaaaaaaa", str2 = "aaaaaaaa"
Output: "aaaaaaaa"
Constraints:
1 <= str1.length, str2.length <= 1000str1andstr2consist of lowercase English letters.
Solution
Approach: LCS Table, Then Walk Back
A supersequence has to contain every character of str1 and every character of str2. The only way to save length is to let one character serve both strings at once, and the characters that can be shared, in order, form a common subsequence. So the shortest answer shares a longest common subsequence (LCS), and its length is len(str1) + len(str2) - LCS.
First build the usual LCS table: f[i][j] is the LCS length of the first i characters of str1 and the first j characters of str2. If str1[i-1] == str2[j-1] then f[i][j] = f[i-1][j-1] + 1, otherwise f[i][j] = max(f[i-1][j], f[i][j-1]).
Then rebuild the answer backwards, starting at (m, n):
- If
f[i][j] == f[i-1][j], the last character ofstr1is not needed for the LCS: writestr1[i-1]and step up. - Else if
f[i][j] == f[i][j-1], do the same withstr2[j-1]and step left. - Otherwise both last characters are equal and belong to the LCS: write it once and step diagonally.
- When one string runs out (
i == 0orj == 0), copy the rest of the other one.
Every character is written exactly once except the LCS characters, which are shared, so the result has the shortest possible length. Since the characters come out from the end, reverse them at the end.
Complexity: O(m·n) time and O(m·n) space for the table, where m and n are the lengths of the two strings.
class Solution:
def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
m, n = len(str1), len(str2)
# f[i][j] = length of the LCS of str1[:i] and str2[:j]
f = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(1, m + 1):
for j in range(1, n + 1):
if str1[i - 1] == str2[j - 1]:
f[i][j] = f[i - 1][j - 1] + 1
else:
f[i][j] = max(f[i - 1][j], f[i][j - 1])
# Walk back from (m, n), writing the answer from its end.
out = []
i, j = m, n
while i > 0 or j > 0:
if i == 0:
j -= 1
out.append(str2[j])
elif j == 0:
i -= 1
out.append(str1[i])
elif f[i][j] == f[i - 1][j]:
i -= 1
out.append(str1[i])
elif f[i][j] == f[i][j - 1]:
j -= 1
out.append(str2[j])
else: # str1[i - 1] == str2[j - 1] is part of the LCS: write it once
i -= 1
j -= 1
out.append(str1[i])
return "".join(reversed(out))