Skip to content
BASA DSA

Longest Common Subsequence

Medium2-D Dynamic Programming

Return the length of the longest sequence of characters appearing in both strings in the same order, possibly with gaps.

Example 1

Input
text1 = "abcde"
text2 = "ace"
Output
3

Explanation

a,c,e occur in both strings in order, giving length three.

Example 2

Input
text1 = "abc"
text2 = "xyz"
Output
0

Explanation

No character is shared, giving length zero.

Example 3

Input
text1 = "aa"
text2 = "aaa"
Output
2

Explanation

Only two a positions can be selected from the shorter string.

Constraints

  • 1 <= each string length <= 1000
  • Strings contain lowercase English letters

Function contractlongestCommonSubsequenceArguments: json, json
Loading draft…
SolutionRuns on your device
Loading draft…