Longest Common Subsequence - Problem
Given two strings text1 and text2, return the length of their longest common subsequence. If there is no common subsequence, return 0.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
A common subsequence of two strings is a subsequence that is common to both strings.
Input & Output
Example 1 — Basic Case
$
Input:
text1 = "abcde", text2 = "ace"
›
Output:
3
💡 Note:
The longest common subsequence is "ace" with length 3. Characters 'a', 'c', 'e' appear in both strings in the same order.
Example 2 — Partial Match
$
Input:
text1 = "abc", text2 = "abc"
›
Output:
3
💡 Note:
Both strings are identical, so the LCS is the entire string "abc" with length 3.
Example 3 — No Common Subsequence
$
Input:
text1 = "abc", text2 = "def"
›
Output:
0
💡 Note:
No characters are common between the two strings, so LCS length is 0.
Constraints
- 1 ≤ text1.length, text2.length ≤ 1000
- text1 and text2 consist of only lowercase English characters.
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two strings text1="abcde" and text2="ace"
2
Process
Find longest subsequence preserving character order
3
Output
Length of LCS = 3 (subsequence "ace")
Key Takeaway
🎯 Key Insight: Use dynamic programming to build the solution by comparing characters and taking optimal choices at each step
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code