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
Longest Common Subsequence Problemtext1 = "abcde"abcdetext2 = "ace"aceCommon Subsequence"ace"Length = 3💡 A subsequence maintains relative order but characters don\'t need to be consecutiveOutput: 3The longest common subsequence "ace" has length 3
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
Asked in
Google 45 Amazon 38 Microsoft 32 Facebook 28
125.0K Views
High Frequency
~25 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen