Search⌘ K
AI Features

Longest Common Subsequence

Explore how to solve the longest common subsequence problem using dynamic programming. Learn to identify subsequences and implement an efficient algorithm to find the maximum length shared between two strings while maintaining character order.

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.

Constraints:

  • 11 \leq str1.length 500\leq 500
  • 11 \leq str2.length 500\leq 500
  • str1 and str2 contain only lowercase English characters.

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Technical Quiz
1.

What is the output if the following two strings are given as inputs?

str1 = “educative”, str2 = “education”

A.

55

B.

66

C.

77

D.

88


1 / 5

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5

Try it yourself

Implement your solution in the following coding playground.

JavaScript
usercode > main.js
function longestCommonSubsequence(str1, str2){
// Replace this placeholder return statement with your code
return -1;
}
export {longestCommonSubsequence};
Longest Common Subsequence