Description:
Given two strings str1 and str2, find the length of their longest common subsequence. Return 0 if there is no common subsequence.
Constraints:
1 <= str1.length, str2.length <= 1000str1andstr2consist of lowercase English letters.
Example 1:
Input: str1 = 'abcdef', str2 = 'acbefd' Output: 4
Example 2:
Input: str1 = 'abcd', str2 = 'efgh' Output: 0
Example 3:
Input: str1 = 'abc', str2 = 'abc' Output: 3
Example 4:
Input: str1 = '', str2 = 'abc' Output: 0
- Build a 2D array where
dp[i][j]is the length of the LCS ofstr1[i:]andstr2[j:].
Steps:
- Create a 2D array
dpof size(m+1) x (n+1)initialized to 0, wheremandnare the lengths ofstr1andstr2. - Iterate
ifromm-1to0andjfromn-1to0:- If
str1[i] == str2[j], setdp[i][j] = 1 + dp[i+1][j+1]. - Else, set
dp[i][j] = max(dp[i+1][j], dp[i][j+1]).
- If
- The answer is
dp[0][0].
- Recursively compute the LCS length, memoizing results to avoid recomputation.
Steps:
- Define a helper function with indices
iandjforstr1andstr2. - If either index reaches the end of its string, return 0.
- If the result for
(i, j)is memoized, return it. - If
str1[i] == str2[j], return1 + helper(i+1, j+1). - Else, return
max(helper(i+1, j), helper(i, j+1)). - Memoize and return the result.
- After filling the DP table, trace back from
dp[0][0]to reconstruct the LCS string.
Steps:
- Start at
i = 0, j = 0. - If
str1[i] == str2[j], add the character to the LCS and increment both indices. - Else, move in the direction of the larger value between
dp[i+1][j]anddp[i][j+1]. - Repeat until the end of either string is reached.
| Approach | Time Complexity | Space Complexity | Notes |
|---|---|---|---|
| DP (2D Array) | O(m * n) | O(m * n) | Standard, reconstructs LCS |
| Recursive+Memo | O(m * n) | O(m * n) | Elegant, not as fast for large input |
Time and Space complexity:
- The dynamic programming approach has a time complexity of
O(m * n), wheremandnare the lengths of the two strings. The space complexity is alsoO(m * n)due to the 2D DP array. - The recursive with memoization approach also has a time complexity and space complexity of
O(m * n)due to memoization.
