Skip to main content

Longest Common Subsequence

Medium Subject: 2-D Dynamic Programming
Time Complexity
O(M * N)
Space Complexity
O(M * N)

Problem Description

Problem Statement

Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.

Example 1:

  • Input: text1 = "abcde", text2 = "ace"
  • Output: 3
  • Explanation: The longest common subsequence is "ace".

Optimal Solution

Python

Approach: 2-D DP

We use a 2D array dp[i][j] representing the LCS of text1[0...i-1] and text2[0...j-1]. If the characters match, dp[i][j] = 1 + dp[i-1][j-1]. If they don't, we take the max of ignoring the current char of text1 or text2: max(dp[i-1][j], dp[i][j-1]).

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        m, n = len(text1), len(text2)
        dp = [[0] * (n + 1) for _ in range(m + 1)]

        for i in range(1, m + 1):
            for j in range(1, n + 1):
                if text1[i-1] == text2[j-1]:
                    dp[i][j] = 1 + dp[i-1][j-1]
                else:
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1])

        return dp[m][n]