Skip to main content

🟨 Longest Common Subsequence (#1143)

📋 Problem Statement

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

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

💡 Examples

Example 1

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

Example 2

Input: text1 = "abc", text2 = "abc"
Output: 3

🔑 Key Insights & Approach

Core Observation: If chars match, take 1 + LCS of remaining. Otherwise, max of (skip char1, skip char2).

Why 2D DP?

  • O(m * n) time and space
  • Can optimize to O(min(m,n)) space
  • Classic sequence DP

Pattern: "2D String DP" pattern.

🐍 Solution: Python

Approach: 2D DP

Time Complexity: O(m * n) | Space Complexity: O(m * n)

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] = dp[i-1][j-1] + 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])

return dp[m][n]

🔵 Solution: Golang

Approach: 2D DP

Time Complexity: O(m * n) | Space Complexity: O(m * n)

func longestCommonSubsequence(text1 string, text2 string) int {
m, n := len(text1), len(text2)
dp := make([][]int, m+1)
for i := range dp {
dp[i] = make([]int, n+1)
}

for i := 1; i <= m; i++ {
for j := 1; j <= n; j++ {
if text1[i-1] == text2[j-1] {
dp[i][j] = dp[i-1][j-1] + 1
} else {
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
}
}
}

return dp[m][n]
}

func max(a, b int) int {
if a > b { return a }
return b
}

📚 References