Longest Common Subsequence using Dynamic programming (DP)

Here we are going to learn how to find length of longest common subsequence in two strings?
Submitted by Ritik Aggarwal, on November 08, 2018

Problem: You are given two string of length N and M respectively. You have to find the length longest common subsequence.

Constraints:

```    1 <= N <= 10^3
1 <= M <= 10^3
```

Example:

```    Input:
helo
heoa

Output:
3
```

Explanation of the problem:

In the sample input given above, "heo" from "helo" and "heo" from "heoa" is the longest subsequence so the length of Longest Common Subsequence is 3.

Solution:

Before going to the code we can see that recursive solution will show time limit exceeded. As recursive solution has time complexity as O(2^(N+M)). So we definitely have to use dp. I will be using a 2D- matrix in which jth cell of ith row represent the longest common subsequence in the string 1 (ith index to the end) and string 2 (jth index till end).

So now is the code of above approach:

```#include <iostream>
using namespace std;

int LCS(string s1, string s2){
int dp[s1.length()+1][s2.length() + 1] = {0};
for(int row = s1.length() - 1;row>=0;row--){
for(int col = s2.length()-1;col>=0;col--){
if(s1[row] == s2[col]){
dp[row][col] = dp[row + 1][col + 1] + 1;
}else{
dp[row][col] = max(dp[row+1][col], dp[row][col+1]);
}
}
}
return dp;
}

int main(){
string s1, s2;

cin >> s1;
cin >> s2;
cout << LCS(s1,s2) << endl;

return 0;
}
```

Output

```helo
heoa
3
```

I have used the bottom approach and the time complexity of this approach is O(N * M).

TOP Interview Coding Problems/Challenges

Learn PCB Designing: PCB DESIGNING TUTORIAL

 Recommended posts C Tips & Tricks, C++ Tips & Tricks Introduction to Linux (Its modes, Safety, Most popular Applications) Linux Best Distros of 2018 C programming optimization techniques Differences b/w C & Embedded C? Embedded C Interview Q. & A. C programming tips for Embedded Development Basic rules of writing a C program Important points (rules) to remember while writing C/C++ program Top 5 Websites for solving programming challenges Read more...

 Others... Computer G.K. (MCQ) Most viewed pages... Categories...

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates