</>

1143. Longest Common Subsequence

Medium NeetCode 150
2-D Dynamic Programming Time O(M*N) Space O(N)
↗ Open on LeetCode Source: NeetCode 150

Quick review

Pattern
2-D Dynamic Programming
Time
O(M*N)
Space
O(N)

Standard Solution (C++)

SummaryGiven two strings, find the length of their longest common subsequence — a sequence of characters that appears in both strings in the same relative order, though not necessarily contiguously.

Approach
  • Build a 2-D DP table where dp[i][j] holds the LCS length for the first i characters of text1 and j characters of text2.
  • If the current characters match, dp[i][j] = dp[i-1][j-1] + 1 — extend the LCS by one.
  • Otherwise, dp[i][j] = max(dp[i-1][j], dp[i][j-1]) — take the best result from ignoring one character from either string.
  • The base case (empty prefix of either string) naturally fills the zero-padded border row and column.
#include <string>
#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int m = text1.size(), n = text2.size();

        // dp[i][j] = LCS length for text1[0..i-1] and text2[0..j-1]
        // Row 0 and column 0 are implicitly 0 (empty prefix base case).
        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) {
                if (text1[i - 1] == text2[j - 1]) {
                    // Characters match: extend the diagonal result
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    // No match: carry forward the best from either direction
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }

        return dp[m][n];
    }
};
Time O(m * n) Space O(m * n)

A canonical reference solution. Problem statement © LeetCode — see the official link above.

My Solution (C++)

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        int len1=text1.length();
        int len2=text2.length();
        vector<int> dp(len2+1, 0);

        // update dp row by row
        for(int i=1; i<=len1; ++i){
            int prev_diag=0;
            for(int j=1; j<=len2; ++j){
                int tmp=dp[j];
                if(text1[i-1]==text2[j-1]){ // text1 and text2 are 0-indexed
                    dp[j]=prev_diag+1;
                }
                else{
                    dp[j]=std::max(dp[j], dp[j-1]);
                }
                prev_diag=tmp;
            }
        }

        return dp[len2];
    }
};

// Time Complexity: O(M*N)
// Space Complexity: O(N)
Time O(M*N) Space O(N)

My own solution and notes, as I wrote them.

▶ Run it — editable in-browser playground with a sample driver C++

Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.

C++ ▶ Runnable Auto-generated driver with sample input — unverified.

Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.

Related — same pattern