Taro Logo

Longest Common Subsequence

Medium
1 views
2 months ago

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

A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

  • For example, "ace" is a subsequence of "abcde".

A common subsequence of two strings is a subsequence that is common to both strings.

Example 1:

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

Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.

Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: There is no such common subsequence, so the result is 0.

Constraints:

  • 1 <= text1.length, text2.length <= 1000
  • text1 and text2 consist of only lowercase English characters.
Sample Answer
## Longest Common Subsequence

### Problem Description

Given two strings `text1` and `text2`, the goal is to find the length of their longest common subsequence. 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. A common subsequence is a subsequence common to both strings. If there is no common subsequence, return 0.

### Naive Solution (Brute Force)

The brute force approach involves generating all possible subsequences of both strings and finding the longest common one. This method is highly inefficient.

### Optimal Solution (Dynamic Programming)

We can use dynamic programming to solve this problem efficiently. Let `dp[i][j]` be the length of the longest common subsequence of `text1[0...i-1]` and `text2[0...j-1]`. Then, the recurrence relation is as follows:

- If `text1[i-1] == text2[j-1]`, then `dp[i][j] = dp[i-1][j-1] + 1`
- Else, `dp[i][j] = max(dp[i-1][j], dp[i][j-1])`

The base case is `dp[0][j] = 0` for all `j` and `dp[i][0] = 0` for all `i`.

### Code Implementation (Java)

```java
class Solution {
    public int longestCommonSubsequence(String text1, String text2) {
        int n = text1.length();
        int m = text2.length();
        int[][] dp = new int[n + 1][m + 1];

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

        return dp[n][m];
    }
}

Code Implementation (Python)

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

        for i in range(1, n + 1):
            for j in range(1, m + 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[n][m]

Example

text1 = "abcde", text2 = "ace"

ace
0000
a0111
b0111
c0122
d0122
e0123

Result: 3

Time Complexity Analysis

The time complexity is O(n*m), where n is the length of text1 and m is the length of text2. This is because we are iterating through each cell in the dp array, which has dimensions (n+1) x (m+1).

Space Complexity Analysis

The space complexity is O(n*m) because we are using a 2D array dp of size (n+1) x (m+1) to store the lengths of the longest common subsequences.

Edge Cases

  1. Empty Strings: If either text1 or text2 is empty, the longest common subsequence is 0.
  2. Identical Strings: If text1 and text2 are identical, the longest common subsequence is the length of either string.
  3. No Common Characters: If there are no common characters between text1 and text2, the longest common subsequence is 0.