Shortest Common Supersequence (LeetCode 1092): Solution and Explanation

Hard
String
Dynamic Programming

Return the shortest string that contains both str1 and str2 as subsequences. Any shortest answer is accepted.

Intuition

A supersequence must contain every letter of both strings in order. The only way to make it shorter than str1 + str2 is to let some letters serve both strings at once.

The letters that serve both strings appear in the same order in each, so they form a common subsequence. The longest common subsequence (LCS) shares the most, which makes the answer length m + n - LCS.

Knowing the length is not enough; you have to build the string. The LCS table already records, for every pair of prefixes, which move keeps the most sharing. Walking back from the bottom-right corner and following those moves spells out the answer from right to left.

Approach: LCS table plus traceback

  1. Fill dp[i][j] = LCS length of str1[:i] and str2[:j]: equal letters give dp[i-1][j-1] + 1, otherwise max(dp[i-1][j], dp[i][j-1]).
  2. Start at i = m, j = n with an empty result list.
  3. If str1[i-1] == str2[j-1], append that letter once and move to (i-1, j-1).
  4. Otherwise, if dp[i-1][j] >= dp[i][j-1], append str1[i-1] and move up; else append str2[j-1] and move left.
  5. When one string runs out, append the rest of the other. Reverse the list and join it.

Step-by-step example

str1 = "abac", str2 = "cab"
  1. The LCS table ends with dp[4][3] = 2 (the shared letters "ab"), so the answer has 4 + 3 - 2 = 5 letters.
  2. At (4,3): 'c' vs 'b' differ. dp[3][3] = 2 beats dp[4][2] = 1, so write 'c' from str1 and move up.
  3. At (3,3): 'a' vs 'b' differ. dp[2][3] = 2 beats dp[3][2] = 1, so write 'a' from str1 and move up.
  4. At (2,3): 'b' == 'b', write 'b' once. At (1,2): 'a' == 'a', write 'a' once. Now str1 is used up, so copy the leftover 'c' from str2.
  5. Collected right to left: c, a, b, a, c. Reversed, the answer is "cabac".

Code: Python, Java, C++

1class Solution:
2    def shortestCommonSupersequence(self, str1: str, str2: str) -> str:
3        m, n = len(str1), len(str2)
4        dp = [[0] * (n + 1) for _ in range(m + 1)]
5        for i in range(1, m + 1):
6            for j in range(1, n + 1):
7                if str1[i - 1] == str2[j - 1]:
8                    dp[i][j] = dp[i - 1][j - 1] + 1
9                else:
10                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
11        res = []
12        i, j = m, n
13        while i > 0 and j > 0:
14            if str1[i - 1] == str2[j - 1]:
15                res.append(str1[i - 1])
16                i -= 1
17                j -= 1
18            elif dp[i - 1][j] >= dp[i][j - 1]:
19                res.append(str1[i - 1])
20                i -= 1
21            else:
22                res.append(str2[j - 1])
23                j -= 1
24        while i > 0:
25            res.append(str1[i - 1])
26            i -= 1
27        while j > 0:
28            res.append(str2[j - 1])
29            j -= 1
30        return ''.join(reversed(res))
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m * n)

Filling the table touches each of the (m + 1) x (n + 1) cells once; the walk back takes at most m + n steps.

Space

O(m * n)

The whole table is needed for the walk back, because the path can visit any row.

Other approaches

Build the LCS string, then merge (time O(m * n), space O(m * n))

Recover the LCS itself, then walk both strings and the LCS together: copy letters of str1 and str2 until each reaches the next LCS letter, write that letter once, and continue.

DP that stores whole strings (time O(m * n * (m + n)), space O(m * n * (m + n)))

Let dp[i][j] hold the shortest supersequence itself instead of a length. Easy to write but each cell copies a string of up to m + n letters.

Common mistakes

  • Stopping the walk when either index hits zero and forgetting the leftovers. The unused prefix of the other string still has to be written.
  • Appending letters in forward order. The traceback moves from the end of both strings to the start, so the collected letters must be reversed.
  • Choosing the wrong side on a mismatch. You must move toward the neighbour with the larger LCS value; moving the other way loses a shared letter and makes the result longer.
  • Expecting one exact answer. Different tie breaks give different but equally short strings, and any of them is accepted.

Frequently asked questions

Why is the answer length m + n - LCS?

Every letter of both strings must appear. A letter can count for both strings only if those shared letters appear in the same order in each, which makes them a common subsequence. The most you can share is the LCS, and each shared letter saves one.

Is the answer unique?

No. For "a" and "b" both "ab" and "ba" work. The judge checks the length and that both strings are subsequences, so any shortest answer passes.

Can I save memory with rolling rows?

Not easily for this problem. The length alone needs two rows, but rebuilding the string needs the full table, or a divide-and-conquer method like Hirschberg's algorithm.