/*
To implement an efficient Dynamic Programming algorithm to find the Longest Common Subsequence (LCS) of two given strings.

Given two strings:
X = "abade"
Y = "bade"
Find the Longest Common Subsequence (LCS) and its length.

Algorithm
Create a DP table dp[n+1][m+1] initialized with 0.
Traverse both strings:
If characters match →
dp[i][j] = 1 + dp[i-1][j-1]
Else →
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
After filling the table, backtrack from dp[n][m]:
If characters match → include in LCS
Else move in direction of larger value
Reverse the obtained string to get final LCS.
*/

#include <bits/stdc++.h>
using namespace std;

int main() {
    string X = "abade";
    string Y = "bade";

    int n = X.size(), m = Y.size();

    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));

    // Build DP table
    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= m; ++j) {
            if (X[i - 1] == Y[j - 1])
                dp[i][j] = dp[i - 1][j - 1] + 1;
            else
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
        }
    }

    // Reconstruct LCS
    string lcs = "";
    int i = n, j = m;

    while (i > 0 && j > 0) {
        if (X[i - 1] == Y[j - 1]) {
            lcs += X[i - 1];
            --i; --j;
        } else if (dp[i - 1][j] > dp[i][j - 1]) {
            --i;
        } else {
            --j;
        }
    }

    reverse(lcs.begin(), lcs.end());

    cout << "Length of LCS: " << dp[n][m] << endl;
    cout << "LCS: " << lcs << endl;

    return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: