Menu
CoddyTech

Longest Common Subsequence

You get two strings, text1 and text2. A subsequence of a string keeps some of its letters in their original order and drops the rest; the kept letters do not have to be neighbors. Return the length of the longest string that is a subsequence of both, or 0 if the two strings have no letter in common.

Function

longestCommonSubsequence(text1: string, text2: string) → integer
text1string
the first string
text2string
the second string
Returnsinteger
the length of the longest common subsequence

Constraints

  • 1 ≤ text1.length ≤ 1000
  • 1 ≤ text2.length ≤ 1000
  • Both strings contain only lowercase English letters.

Examples

Input
text1 = "stone"text2 = "longest"
Output
3
Explanation
o, n, e appear in this order in both words, so one is a common subsequence of length 3. In longest the letters s and t come last, while in stone they come first, so a common subsequence that uses them can only be st, which is shorter.

lock icon+19 hidden tests on Submit

challenge icon

Follow-up

Can you return one longest common subsequence itself, not only its length?

Reset code
def longestCommonSubsequence(text1, text2):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

text1 = "stone"
text2 = "longest"

Expected

3