Skip to content

Commit 944db86

Browse files
committed
updated explaination.md and time and space complexity
1 parent f0bd5e7 commit 944db86

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
Shortest Common Supersequence Solution
2+
Overview
3+
The goal of this solution is to find the shortest common supersequence (SCS) of two given strings, str1 and str2. The shortest common supersequence is the shortest string that has both str1 and str2 as subsequences.
4+
5+
Steps
6+
Create DP Table:
7+
8+
We first create a dynamic programming (DP) table dp of size (m + 1) x (n + 1), where m is the length of str1 and n is the length of str2.
9+
10+
Fill the DP Table:
11+
12+
We fill the DP table based on the following conditions:
13+
14+
If characters of str1 and str2 match, we take the diagonal value and add 1: dp[i][j] = dp[i - 1][j - 1] + 1.
15+
16+
If characters do not match, we take the maximum value from the left or the top cell: dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]).
17+
18+
Build the Shortest Common Supersequence:
19+
20+
We use a StringBuilder to construct the SCS.
21+
22+
Starting from the bottom-right corner of the DP table, we move based on the values in the DP table:
23+
24+
If characters match, we add that character to the result and move diagonally up-left.
25+
26+
If characters do not match, we move in the direction of the larger DP value (either up or left).
27+
28+
Finally, we add any remaining characters from str1 or str2.
29+
30+
Reverse the Result:
31+
32+
The result is constructed in reverse order, so we reverse it before returning.
33+
34+
Time Complexity
35+
The time complexity is O(m * n) because we traverse the DP table of size (m + 1) x (n + 1).
36+
37+
Space Complexity
38+
The space complexity is O(m * n) because we use a DP table of size (m + 1) x (n + 1).

DP/#1092 - Shortest Common Supersequence - Hard/Shortest Common Supersequence.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,4 +50,7 @@ public String shortestCommonSupersequence(String str1, String str2) {
5050
// Reverse the result before returning
5151
return result.reverse().toString();
5252
}
53-
}
53+
}
54+
55+
//Time Complexity : O(m*n)
56+
//Space Complexity : O(m*n)

0 commit comments

Comments
 (0)