Shortest Common Supersequence
LeetCode 1092 · Hard · solution, intuition & step-by-step walkthrough
LCS table, then reconstruct while emitting skipped characters.
This is how I solved Shortest Common Supersequence (LeetCode 1092), a hard problem from the LCS pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
The shortest string containing both is built around their longest common subsequence: shared characters are written once, and every other character from either string is inserted around them. Fill the LCS table, then walk it, emitting characters as you move.
Approach
- 1
Bottom-up LCS table from the ends.
- 2
Walk i, j from the start: equal → emit once, advance both.
- 3
Otherwise follow the larger LCS value and emit the character you skip.
- 4
Append whatever remains of either string.
How I solved it
LCS + reconstructionPythonO(m·n) time
class Solution:
def shortestCommonSupersequence(self, str1, str2):
m = len(str1)
n = len(str2)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if str1[i] == str2[j]:
dp[i][j] = 1 + dp[i + 1][j + 1]
else:
dp[i][j] = max(dp[i + 1][j], dp[i][j + 1])
i = 0
j = 0
result = ""
while i < m and j < n:
if str1[i] == str2[j]:
result += str1[i]
i += 1
j += 1
elif dp[i + 1][j] > dp[i][j + 1]:
result += str1[i] # in LCS we'd omit this
i += 1
else:
result += str2[j] # in LCS we'd omit this
j += 1
while i < m:
result += str1[i]
i += 1
while j < n:
result += str2[j]
j += 1
return resultShortest Common Supersequence — FAQ
What is the intuition behind Shortest Common Supersequence?
The shortest string containing both is built around their longest common subsequence: shared characters are written once, and every other character from either string is inserted around them. Fill the LCS table, then walk it, emitting characters as you move.
How do you solve Shortest Common Supersequence (LeetCode 1092)?
1. Bottom-up LCS table from the ends. 2. Walk i, j from the start: equal → emit once, advance both. 3. Otherwise follow the larger LCS value and emit the character you skip. 4. Append whatever remains of either string.
What is the time and space complexity of Shortest Common Supersequence?
Time: O(m · n). Space: O(m · n). (Accepted approach: LCS + reconstruction.)
What are common mistakes in Shortest Common Supersequence?
Characters you'd skip for the LCS must still appear in the supersequence.