This approach uses dynamic programming to solve the problem by creating a 2D table to store the lengths of the longest common subsequences for different substrings. Each cell dp[i][j]
in the table represents the longest common subsequence length of substrings text1[0..i-1]
and text2[0..j-1]
. The table is filled using the following rules:
text1[i-1]
and text2[j-1]
are equal, then dp[i][j] = dp[i-1][j-1] + 1
.dp[i][j] = max(dp[i-1][j], dp[i][j-1])
.The final answer is dp[text1.length][text2.length]
.
Time Complexity: O(n*m), where n and m are the lengths of text1
and text2
respectively.
Space Complexity: O(n*m) for the DP table.
1def longest_common_subsequence(text1, text2):
2 n, m = len(text1), len(text2)
3 dp = [[0] * (m + 1) for _ in range(n + 1)]
4
5 for i in range(1, n + 1):
6 for j in range(1, m + 1):
7 if text1[i - 1] == text2[j - 1]:
8 dp[i][j] = dp[i - 1][j - 1] + 1
9 else:
10 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
11
12 return dp[n][m]
13
14print(longest_common_subsequence("abcde", "ace"))
This Python solution defines a function longest_common_subsequence
which calculates the LCS using a dynamic programming table dp
. Each entry in dp
is filled based on the character comparison and prior calculated results for subsequences.
This optimization reduces space complexity by only storing data for the current and the previous row. The idea remains the same - calculating the LCS length incrementally using a dynamic programming strategy. However, instead of a full 2D table, only two 1D arrays are used, effectively reducing space usage from O(n*m) to O(min(n, m)). This is achieved by noting that each row of the DP table depends only on the previous row. So, we use two arrays that swap every iteration.
Time Complexity: O(n*m), where n is the length of text1
and m is the length of text2
.
Space Complexity: O(min(n, m))
1function longestCommonSubsequence(text1, text2) {
2 if (text1.length < text2.length) {
3 [text1, text2] = [text2, text1];
4 }
5 const n = text1.length;
6 const m = text2.length;
7
8 let previous = Array(m + 1).fill(0);
9 let current = Array(m + 1).fill(0);
10
11 for (let i = 1; i <= n; i++) {
12 current.fill(0);
13 for (let j = 1; j <= m; j++) {
14 if (text1[i - 1] === text2[j - 1]) {
15 current[j] = previous[j - 1] + 1;
16 } else {
17 current[j] = Math.max(previous[j], current[j - 1]);
18 }
19 }
20 [previous, current] = [current, previous];
21 }
22
23 return previous[m];
24}
25
26console.log(longestCommonSubsequence("abcde", "ace"));
The JavaScript solution effectively reduces the space requirement by using two arrays and iteratively swapping them, allowing for space-efficient storage of LCS computation. This makes it suitable for handling larger input sizes within a limited space budget.