Longest Common Subsequence
1 approach, code in every language
Problem description
You are given two strings, text1 and text2. A subsequence keeps the original relative order of characters but may skip any number of them; a common subsequence is one that appears in both strings.
Return the length of the longest subsequence present in both text1 and text2. If no common subsequence exists, return 0.
Example 1
Input: text1 = "abcde", text2 = "ace"
Output: 3
The subsequence "ace" appears in both strings and no longer common subsequence exists, so the answer is 3.
Example 2
Input: text1 = "abc", text2 = "def"
Output: 0
The two strings share no characters, so the longest common subsequence has length 0.
Constraints
1 <= text1.length, text2.length <= 1000text1 and text2 consist of lowercase English characters.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Shared Checkpoint Order is our own problem on the technique behind Longest Common Subsequence: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free