Tutorialspoint
Problem
Solution
Submissions

Longest Common Subsequence of two Strings

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C# program to find the longest common subsequence (LCS) of two strings. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. The longest common subsequence is the longest sequence that is a subsequence of both strings.

Example 1
  • Input: text1 = "abcde", text2 = "ace"
  • Output: 3
  • Explanation:
    • The longest common subsequence is "ace" with length 3.
Example 2
  • Input: text1 = "abc", text2 = "def"
  • Output: 0
  • Explanation:
    • There is no common subsequence between the two strings.
Constraints
  • 1 ≤ text1.length, text2.length ≤ 1000
  • text1 and text2 consist of only lowercase English characters
  • Time Complexity: O(m*n) where m and n are the lengths of the two strings
  • Space Complexity: O(m*n) for the dynamic programming table
ArraysStringsCapgeminiShopify
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming to solve this problem.
  • Create a 2D array to store the lengths of LCS for different subproblems.
  • If characters at current positions match, add 1 to the LCS of the strings without these characters.
  • If characters don't match, take the maximum of LCS by excluding either character.
  • The value in the bottom-right cell will be the length of the LCS.

Steps to solve by this approach:

 Step 1: Define the problem in terms of overlapping subproblems (to use dynamic programming).
 Step 2: Create a 2D array dp where dp[i,j] represents the length of LCS of text1[0..i-1] and text2[0..j-1].
 Step 3: Initialize the first row and first column of dp with 0 (base case: empty string has 0 LCS with any string).
 Step 4: For each character in text1 and text2, if they match, dp[i,j] = dp[i-1,j-1] + 1.
 Step 5: If they don't match, dp[i,j] = max(dp[i-1,j], dp[i,j-1]).
 Step 6: Complete filling the dp table by iterating through both strings.
 Step 7: The value in dp[m,n] gives the length of the LCS of the entire strings.

Submitted Code :