[Geeks for Geeks] Longest Common Subsequence

Longest Common Subsequence

Given two sequences, find the length of longest subsequence present in both of them. Both the strings are of uppercase.

  • Time : O(xy)
  • Space : O(min(x,y))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
//Function to find the length of longest common subsequence in two strings.
int lcs(int x, int y, string s1, string s2) {
if(x < y) return lcs(y, x, s2, s1);
vector<int> dp(y + 1);

for(int i = 1; i <= x; i++) {
vector<int> ndp(y + 1);
for(int j = 1; j <= y; j++) {
if(s1[i-1] == s2[j-1]) ndp[j] = dp[j-1] + 1;
else ndp[j] = max(dp[j], ndp[j-1]);
}
swap(ndp, dp);
}

return dp[y];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/longest-common-subsequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.