...

/

Longest Common Subsequence

Longest Common Subsequence

Let's solve the Longest Common Subsequence problem using Dynamic Programming.

Statement

Suppose you are given two strings. You need to find the length of the longest common subsequence between these two strings.

A subsequence is a string formed by removing some characters from the original string, while maintaining the relative position of the remaining characters. For example, “abd” is a subsequence of “abcd”, where the removed character is “c”.

If there is no common subsequence, then return 0.

Let’s say you have the following two strings:

  • “cloud”
  • “found”

The longest common subsequence between these two strings is “oud”, which has a length of 33.

Constraints:

  • 1<=1 <= str1.length <=2.5×103<= 2.5\times10^3
  • 1<=1 <= str2.length <=2.5×103<= 2.5\times10^3
  • str1 and str2 contain only lowercase English characters.

Examples

No.

str1

str2

length

1

"bald"

"bad"

3

2

"nocturnal"

"nick"

2

3

"card"

"tissue"

0

Try it yourself

Implement your solution in the following coding playground.

Press + to interact
C++
usercode > main.cpp
#include <iostream>
#include <string>
int LongestCommonSubsequence(std::string str1, std::string str2){
// Write your code here
// your code will replace the placeholder return statement below
return -1;
}
Longest Common Subsequence

Note: If you clicked the “Submit” button and the code timed out, this means that your solution needs to be optimized in terms of running time.

Hint: Use dynamic programming and see the magic.

Solution

We will first explore the naive recursive solution to this problem and then see how it can be improved using the Longest Common Substring dynamic programming pattern.

Naive approach

A naive approach is to compare the characters of both strings based on the following rules:

  • If the current characters of both strings match, we move one position ahead in both strings. ...

Access this course and 1400+ top-rated courses and projects.