49. Shortest Common Supersequence

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.

(A string S is a subsequence of string T if deleting some number of characters from T (possibly 0, and the characters are chosen anywhere from T) results in the string S.)

Example 1:

Input: str1 = "abac", str2 = "cab"
Output: "cabac"
Explanation: 
str1 = "abac" is a subsequence of "cabac" because we can delete the first "c".
str2 = "cab" is a subsequence of "cabac" because we can delete the last "ac".
The answer provided is the shortest such string that satisfies these properties.

Solution: (Find the longest common subsequence)

class Solution
{
public:
    string findLCS(string &s1, string &s2)
    {
        int n = s1.length();
        int m = s2.length();

        if (n == 0 || m == 0)
        {
            return "";
        }

        vector<vector<string>> dp(n + 1, vector<string>(m + 1, ""));

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= m; j++)
            {
                if (s1[i - 1] == s2[j - 1])
                {
                    dp[i][j] = dp[i - 1][j - 1] + s1[i - 1];
                }
                else
                {
                    string exci = dp[i - 1][j];
                    string excj = dp[i][j - 1];

                    dp[i][j] = (exci.length()> excj.length()) ? exci : excj;
                }
            }
        }

        return dp[n][m];
    }

    string shortestCommonSupersequence(string &str1, string &str2)
    {
        string lcs = findLCS(str1, str2);

        int k = 0;

        int i = 0, j = 0;

        string res = "";

        while (k < lcs.length())
        {
            while (str1[i] != lcs[k])
            {
                res += str1[i];
                i++;
            }

            while (str2[j] != lcs[k])
            {
                res += str2[j];
                j++;
            }

            res += lcs[k];

            i++;
            j++;
            k++;
        }

        res += str1.substr(i);
        res += str2.substr(j);

        return res;
    }
};

Time Complexity: O(n* m)

Last updated