Problem Description
Given two strings text1 and text2, determine the length of their longest common subsequence. A subsequence is derived from the original string by deleting some (or no) characters without changing the order of the remaining characters. If there is no common subsequence, return 0.
Key Insights
- The problem is well-suited for a dynamic programming approach.
- Use a 2D table where dp[i][j] stores the length of the longest common subsequence for text1[0...i-1] and text2[0...j-1].
- If the characters match at the current position, extend the subsequence by 1 from dp[i-1][j-1]; otherwise, take the maximum from dp[i-1][j] or dp[i][j-1].
- Filling the table in a bottom-up manner ensures that all subproblems are solved optimally.
Space and Time Complexity
Time Complexity: O(m * n), where m and n are the lengths of text1 and text2. Space Complexity: O(m * n) for maintaining the 2D DP table. Space can be optimized to O(min(m, n)) if needed.
Solution
This solution uses a dynamic programming approach with a 2D array (dp) to record the lengths of common subsequences at each substring pair. We initialize a table of dimensions (m+1) x (n+1) with zeros, where m and n are the lengths of text1 and text2. We iterate over both strings, comparing characters; if they match, we set dp[i][j] = dp[i-1][j-1] + 1, otherwise we choose the maximum from dp[i-1][j] and dp[i][j-1]. The final answer is found at dp[m][n].