AlgoLab
AlgorithmsCompare
AlgoLab
AlgorithmsCompareGitHub

© 2026 AlgoLab. Open source.

AlgorithmsDynamic ProgrammingLongest Common Subsequence
Dynamic Programmingintermediatestringsubsequence2d-dpdiff

Longest Common Subsequence

The Longest Common Subsequence (LCS) problem finds the longest sequence of characters that appears in both strings in the same relative order (not necessarily contiguous). The DP solution builds an (m+1)×(n+1) table and runs in O(mn) time, used in diff tools, version control, and bioinformatics.

Complexity

Best
O(mn)
Average
O(mn)
Worst
O(mn)
Space
O(mn)

Visualizer

Implementation

int lcs(string& a, string& b) {
    int m=a.size(), n=b.size();
    vector<vector<int>> dp(m+1,vector<int>(n+1,0));
    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]);
    return dp[m][n];
}

How It Works

1.Recurrence

If a[i]==b[j]: dp[i][j]=dp[i-1][j-1]+1 (extend LCS by one). Otherwise: dp[i][j]=max(dp[i-1][j], dp[i][j-1]) (best LCS ignoring current char of a or b).

2.Reconstruction

To reconstruct the actual LCS string: backtrack from dp[m][n]. If a[i-1]==b[j-1], include the character and go diagonal. Otherwise go in the direction of the larger neighbor.

3.Applications

LCS is the basis of Unix diff, git diff, DNA sequence alignment, and plagiarism detection. The edit distance between two strings is closely related to LCS length.

Related Algorithms

LayoutGridEdit DistanceLayoutGridLongest Increasing SubsequenceLayoutGrid0/1 Knapsack

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms