Tutorialspoint
Problem
Solution
Submissions

Find the Longest Common Subsequence (LCS) of Two Strings.

Certification: Advanced Level Accuracy: 100% Submissions: 2 Points: 15

Write a Python program that finds the longest common subsequence (LCS) between two given strings.

Example 1
  • Input 1: "ABCDEF"
  • Input 2: "AEBDF"
  • Output: "ABDF"
  • Explanation:
    • Step 1: Take the input strings.
    • Step 2: Find the longest common subsequence.
    • Step 3: Return the LCS as the result.
Example 2
  • Input 1: "AGGTAB"
  • Input 2: "GXTXAYB"
  • Output: "GTAB"
  • Explanation:
    • Step 1: Take the input strings.
    • Step 2: Find the longest common subsequence.
    • Step 3: Return the LCS as the result.
Constraints
  • 1 ≤ len(str1), len(str2) ≤ 1000
  • Strings consist of uppercase English letters only.
  • Time Complexity: O(m*n), where m and n are the lengths of the strings.
  • Space Complexity: O(m*n)
StringsDynamic Programming GoogleTutorialspoint
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 dp where dp[i][j] represents the length of the LCS of str1[0:i] and str2[0:j].
  • Fill the dp table by comparing characters of both strings.
  • Reconstruct the LCS from the dp table.

Steps to solve by this approach:

 Step 1: Create a 2D DP table where dp[i][j] represents the LCS length of str1[0...i-1] and str2[0...j-1].
 Step 2: Fill the DP table using bottom-up approach with recurrence relation.
 Step 3: If characters match, dp[i][j] = dp[i-1][j-1] + 1.
 Step 4: If characters don't match, dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
 Step 5: Backtrack through the DP table to reconstruct the actual LCS.
 Step 6: Return the longest common subsequence string.

Submitted Code :