Shortest Common Supersequence

Pattern: Strings DP

hard

The shortest string containing both a and b as subsequences shares their LCS once. Build the LCS table, then walk back from the end: a match is written once, otherwise write the character from the side the table came from.

The problem

Return a shortest string that has both a and b as subsequences. Any shortest answer is accepted: the tests check its length and that both strings are subsequences of it.

Think first

  • How long is the answer?
  • How do you rebuild a string from a DP table?
  • What happens at a match?

Hints

    Brute force, and why it fails

    Try every merge of the two strings: exponential.

    The key insight

    The LCS is the part that can be shared, and the table shows where each other character fits.

    Dry run

    lcs2

    'abac' and 'cab'. Their LCS is 'ab' (length 2).

    Step 1 of 2

    The plan

    fill LCS table
    i, j = m, n
    while i and j: match: add a[i-1], move diagonal; else add from the larger neighbour's side
    add the rest; reverse
    

    Complexity

    Time
    O(m × n)
    Space
    O(m × n)

    The full table is needed to walk back.

    Edge cases

    • One empty string: the other.
    • Equal strings: itself.
    • No common letters: a + b.
    I've built my logic, show the code

    Java

    class Solution {
        public String shortestCommonSupersequence(String a, String b) {
            int m = a.length(), n = b.length();
            int[][] dp = new int[m + 1][n + 1];     // the LCS table: shared characters are written once
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++)
                    dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1) ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]);
            StringBuilder out = new StringBuilder();
            int i = m, j = n;
            while (i > 0 && j > 0) {                // walk back through the table, writing characters from the end
                if (a.charAt(i - 1) == b.charAt(j - 1)) { out.append(a.charAt(i - 1)); i--; j--; }   // shared: once
                else if (dp[i - 1][j] >= dp[i][j - 1]) out.append(a.charAt(--i));   // only in a
                else out.append(b.charAt(--j));                                     // only in b
            }
            while (i > 0) out.append(a.charAt(--i));
            while (j > 0) out.append(b.charAt(--j));
            return out.reverse().toString();
        }
    }

    C++

    class Solution {
    public:
        string shortestCommonSupersequence(string a, string b) {
            int m = static_cast<int>(a.size()), n = static_cast<int>(b.size());
            vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));   // the LCS table: shared characters are written once
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; 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 = m, j = n;
            while (i > 0 && j > 0) {                // walk back through the table, writing characters from the end
                if (a[i - 1] == b[j - 1]) { out += a[i - 1]; i--; j--; }   // shared: once
                else if (dp[i - 1][j] >= dp[i][j - 1]) out += a[--i];      // only in a
                else out += b[--j];                                         // only in b
            }
            while (i > 0) out += a[--i];
            while (j > 0) out += b[--j];
            reverse(out.begin(), out.end());
            return out;
        }
    };

    Python

    class Solution:
        def shortestCommonSupersequence(self, a: str, b: str) -> str:
            m, n = len(a), len(b)
            dp = [[0] * (n + 1) for _ in range(m + 1)]   # the LCS table: shared characters are written once
            for i in range(1, m + 1):
                for j in range(1, n + 1):
                    dp[i][j] = dp[i - 1][j - 1] + 1 if a[i - 1] == b[j - 1] else max(dp[i - 1][j], dp[i][j - 1])
            out, i, j = [], m, n
            while i and j:                          # walk back through the table, writing characters from the end
                if a[i - 1] == b[j - 1]:
                    out.append(a[i - 1])            # shared: once
                    i, j = i - 1, j - 1
                elif dp[i - 1][j] >= dp[i][j - 1]:
                    out.append(a[i - 1])            # only in a
                    i -= 1
                else:
                    out.append(b[j - 1])            # only in b
                    j -= 1
            out.extend(reversed(a[:i]))
            out.extend(reversed(b[:j]))
            return "".join(reversed(out))

    Common mistakes

    • Forgetting the leftover characters.
    • Writing a matched character twice.

    Similar problems