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 (LCS) INPUT text1 = "abcde" a b c d e text2 = "ace" a c e Subsequence: chars in order (not necessarily adjacent) "ace" from "abcde": a b c d e ALGORITHM STEPS 1 Create DP Table dp[i][j] = LCS of text1[0..i] and text2[0..j] 2 Compare Characters If match: dp[i][j] = dp[i-1][j-1]+1 3 No Match Case dp[i][j] = max(dp[i-1][j], dp[i][j-1]) 4 Return Result dp[m][n] is the answer DP Table: "" a c e "" 0 0 0 0 a 0 1 1 1 b 0 1 1 1 c 0 1 2 2 d 0 1 2 2 e 0 1 2 3 FINAL RESULT Longest Common Subsequence: a c e Output: 3 [OK] Length = 3 Matching Visualization: a b c d e a c e Key Insight: LCS uses optimal substructure: if chars match, add 1 to diagonal; otherwise take max of left/top. Time Complexity: O(m*n) where m and n are string lengths. Space: O(m*n) for the DP table. TutorialsPoint - Longest Common Subsequence | Dynamic Programming Approach
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