Skip to content

Commit d884c3a

Browse files
committed
LCS
1 parent 8ba1467 commit d884c3a

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@
8383
- [Min Number of Flips](https://practice.geeksforgeeks.org/problems/min-number-of-flips/0# "view question") - [Cpp Solution](./solutions/Min%20Number%20of%20Flips.cpp)
8484
- [Second most repeated string in a sequence](https://practice.geeksforgeeks.org/problems/second-most-repeated-string-in-a-sequence0534/1# "view question") - [Cpp Solution](./solutions/Second%20most%20repeated%20string%20in%20a%20sequence.cpp)
8585
- [Minimum Swaps for Bracket Balancing](https://practice.geeksforgeeks.org/problems/minimum-swaps-for-bracket-balancing/0# "view question") - [Cpp Solution](./solutions/Minimum%20Swaps%20for%20Bracket%20Balancing.cpp)
86+
- [Longest Common Subsequence](https://practice.geeksforgeeks.org/problems/longest-common-subsequence-1587115620/1 "view question") - [Cpp Solution](./solutions/Longest%20Common%20Subsequence.cpp)
8687
- []( "view question") - [Cpp Solution](./solutions/.cpp)
8788

8889
### Searching & Sorting
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
Longest Common Subsequence
3+
==========================
4+
5+
Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.
6+
7+
Example 1:
8+
Input:
9+
A = 6, B = 6
10+
str1 = ABCDGH
11+
str2 = AEDFHR
12+
Output: 3
13+
Explanation: LCS for input Sequences
14+
“ABCDGH” and “AEDFHR” is “ADH” of
15+
length 3.
16+
17+
Example 2:
18+
Input:
19+
A = 3, B = 2
20+
str1 = ABC
21+
str2 = AC
22+
Output: 2
23+
Explanation: LCS of "ABC" and "AC" is
24+
"AC" of length 2.
25+
Your Task:
26+
Complete the function lcs() which takes the length of two strings respectively and two strings as input parameters and returns the length of the longest subsequence present in both of them.
27+
28+
Expected Time Complexity : O(|str1|*|str2|)
29+
Expected Auxiliary Space: O(|str1|*|str2|)
30+
31+
Constraints:
32+
1<=size(str1),size(str2)<=100
33+
*/
34+
35+
int lcs(int x, int y, string s1, string s2)
36+
{
37+
int dp[x + 1][y + 1];
38+
for (int i = 0; i <= x; ++i)
39+
{
40+
for (int j = 0; j <= y; ++j)
41+
{
42+
if (i == 0 || j == 0)
43+
dp[i][j] = 0;
44+
else
45+
{
46+
if (s1[i - 1] == s2[j - 1])
47+
dp[i][j] = 1 + dp[i - 1][j - 1];
48+
else
49+
{
50+
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
51+
}
52+
}
53+
}
54+
}
55+
56+
return dp[x][y];
57+
}

0 commit comments

Comments
 (0)