Shortest Common Supersequence

Shortest string containing both s1 and s2 as subsequences — LCS DP then reconstruction.

Hard
Time O(n * m) Space O(n * m)
LeetCode
5 min read
dp string

Problem#

Return the shortest string containing both str1 and str2 as subsequences.

Examples#

  • str1 = "abac", str2 = "cab""cabac"

Constraints#

  • 1 <= n, m <= 1000.

Approach#

Compute LCS DP. Reconstruct backwards: when chars match, emit one; when one DP value > the other, emit the corresponding side’s character. Reverse final.

Solution#

Shortest Common Supersequence
class Solution {
public:
string shortestCommonSupersequence(string a, string b) {
int n = a.size(), m = b.size();
vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
dp[i][j] = a[i - 1] == b[j - 1] ? dp[i - 1][j - 1] + 1
: max(dp[i - 1][j], dp[i][j - 1]);
string out;
int i = n, j = m;
while (i > 0 && j > 0) {
if (a[i - 1] == b[j - 1]) { out += a[--i]; --j; }
else if (dp[i - 1][j] > dp[i][j - 1]) out += a[--i];
else out += b[--j];
}
while (i > 0) out += a[--i];
while (j > 0) out += b[--j];
reverse(out.begin(), out.end());
return out;
}
};

Editorial#

The supersequence contains the LCS only once (shared) and everything else from both inputs in interleaved order. Walking back through the DP reconstructs that interleaving — common chars emitted once, others contributed by whichever side dominates.

Complexity#

  • Time: O(n * m).
  • Space: O(n * m).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.