15% off all plans & roadmaps Use code
See plansLeetCode 1092 · Solution & editorial
Given two strings str1 and str2, return the shortest string that has both str1 and str2 as subsequences. If multiple answers exist, you may return any of them.
Shortest Common Supersequence is a Dynamic Programming (DP) Patterns problem, in the 2D Array (Longest Common Subsequence - LCS) subpattern. The pattern covers fibonacci, Kadane, knapsack, LCS, LIS, edit distance, grid paths, and word break
Find longest common subsequence between two strings using 2D DP.
The reference solution runs in O(m * n) time and O(m * n) space.
Shortest Common Supersequence has been reported in interviews at Microsoft, Amazon.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Shortest Common Supersequence is a Dynamic Programming (DP) Patterns problem, in the 2D Array (Longest Common Subsequence - LCS) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.