Below is a step-by-step approach to solve this problem using dynamic programming:
-
Understanding the Subproblem: The key idea is to break down the problem into smaller, more manageable subproblems. We can consider the problem of finding the longest common subsequence of prefixes of the two strings. For any pair of indices
iandj, we consider the longest common subsequence oftext1[0...i]andtext2[0...j]. -
Dynamic Programming Array: We can create a 2D array dp where
dp[i][j]will store the length of the longest common subsequence oftext1[0...i]andtext2[0...j]. -
Base Case: The base case is when either
iorjis 0, which means one of the strings is empty. In this case, the longest common subsequence is 0. -
Recursive Relation: For
dp[i][j], iftext1[i] == text2[j], then the character at indexiandjis part of the longest common subsequence, and we add 1 to the result ofdp[i-1][j-1]. Otherwise, the character at eitheriorjis not part of the longest common subsequence, and we take the maximum ofdp[i-1][j]anddp[i][j-1]. -
Implementation: We iterate over the lengths of the two strings and fill up the
dparray according to the recursive relation. -
Return the Result: The length of the longest common subsequence of text1 and text2 is then
dp[len(text1)][len(text2)].
- Time Complexity:
$O(mn)$ , where$m$ and$n$ are the lengths of the input strings - Space Complexity: similarly,
$O(mn)$ .
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]