Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

Longest Common Subsequence

Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.

Method 1: Naive Recursion Approach

Code

int lcsRec(int x, int y, string s1, string s2)
{
    if (x == 0 || y == 0)
        return 0;

    if (s1[x - 1] == s2[y - 1])
        return 1 + lcs(x - 1, y - 1, s1, s2);
    else
        return max(lcs(x - 1, y, s1, s2), lcs(x, y - 1, s1, s2));
}

Complexity Analysis


DP APPROACHES

A) Memoization(Top-Down)

code


int dp[1001][1001];

void initialize()
{
    for (int i = 0; i < 1001; i++)
        for (int j = 0; j < 1001; j++)
            dp[i][j] = -1;
}
int lcsMo(int x, int y, string s1, string s2)
{
    if (x == 0 || y == 0)
        return 0;

    if (dp[x][y] != -1)
        return dp[x][y];

    if (s1[x - 1] == s2[y - 1])
        return dp[x][y] = 1 + lcs(x - 1, y - 1, s1, s2);
    else
        return dp[x][y] = max(lcs(x, y - 1, s1, s2), lcs(x - 1, y, s1, s2));
}

int lcs(int x, int y, string s1, string s2)
{
    initialize();
    return lcsMo(x, y, s1, s2);
}

Complexity Analysis


B) Tabulation(Bottom up)

int lcs(int x, int y, string s1, string s2)
{
    int dp[x + 1][y + 1];

    for (int i = 0; i < x + 1; i++)
    {
        for (int j = 0; j < y + 1; j++)
        {
            if (i == 0 || j == 0)
                dp[i][j] = 0;
            else if (s1[i - 1] == s2[j - 1])
                dp[i][j] = 1 + dp[iw - 1][j - 1];
            else
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        }
    }
    return dp[x][y];
}

Complexity Analysis

References