Complete-Preparation

πŸŽ‰ One-stop destination for all your technical interview Preparation πŸŽ‰

View the Project on GitHub

Shortest Common Supersequence 🌟🌟🌟

Solution

string shortestSupersequence(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++) {
            if (a[i - 1] == b[j - 1])
                dp[i][j] = 1 + dp[i - 1][j - 1];
            else
                dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
        }
    }

    // Finding and printing the shortest common supersequence
    string res = "";
    int i = n, j = m;
    while (i > 0 && j > 0) {
        if (a[i - 1] == b[j - 1]) {
            res += a[i - 1];
            i--;
            j--;
        }
        else {
            if (dp[i - 1][j] > dp[i][j - 1]) {
                res += a[i - 1];
                i--;
            }
            else {
                res += b[j - 1];
                j--;
            }
        }
    }

    // check if any character of a is left
    while (i > 0) {
        res += a[i - 1];
        i--;
    }

    // check if any character of b is left
    while (j > 0) {
        res += b[j - 1];
        j--;
    }

    // Reverse the string
    reverse(res.begin(), res.end());

    return res;
}