25. Longest common subsequence

Given two strings str1 and str2, find the length of their longest common subsequence.

A subsequence is a sequence that appears in the same relative order but not necessarily contiguous and a common subsequence of two strings is a subsequence that is common to both strings.

Example 1:

Input: str1 = "bdefg", str2 = "bfg"

Output: 3

Explanation: The longest common subsequence is "bfg", which has a length of 3.

Example 2:

Input: str1 = "mnop", str2 = "mnq"

Output: 2

Explanation: The longest common subsequence is "mn", which has a length of 2.

Now Your Turn!

Pick the correct output for the given input

Input: str1 = "abc", str2 = "dafb"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • n=str1.length
  • m=str2.length
  • 1<= n, m <=103
  • str1 and str2 are in lowercase alphabet

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
int lcs(string str1, string str2) {
 
}
};
 
Test Case

Input:

M
N
Str1
Str2