Tutorialspoint
Problem
Solution
Submissions

Longest Common Subsequence

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C++ program to find the longest common subsequence (LCS) of two strings. The LCS is the longest sequence of characters that appears in the same order in both strings, but not necessarily consecutively.

Example 1
  • Input: string1 = "abcde" string2 = "ace"
  • Output: 3
  • Explanation:
    • Step 1: Create a dynamic programming table to store the length of LCS for different subproblems.
    • Step 2: Fill the table by comparing characters of both strings.
    • Step 3: The longest common subsequence is "ace" which has a length of 3.
    • Step 4: Return the length of the LCS.
Example 2
  • Input: string1 = "AGGTAB" string2 = "GXTXAYB"
  • Output: 4
  • Explanation:
    • Step 1: Create a dynamic programming table to store the length of LCS for different subproblems.
    • Step 2: Fill the table by comparing characters of both strings.
    • Step 3: The longest common subsequence is "GTAB" which has a length of 4.
    • Step 4: Return the length of the LCS.
Constraints
  • 1 ≤ length of strings ≤ 1000
  • Time Complexity: O(m * n), where m and n are the lengths of the two strings
  • Space Complexity: O(m * n)
ArraysStringsDynamic Programming AccentureAdobe
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 the longest common subsequences of substrings.
  • Fill the array based on the characters of the two strings.
  • The value in the last cell of the array will be the length of the LCS.

Steps to solve by this approach:

 Step 1: Create a 2D array dp[m+1][n+1] where m and n are lengths of two strings.

 Step 2: Initialize all entries of first row and first column to 0.
 Step 3: For each character pair (i,j), compare characters at position i-1 in first string and j-1 in second string.
 Step 4: If characters match, dp[i][j] = dp[i-1][j-1] + 1.
 Step 5: If characters don't match, dp[i][j] = max(dp[i-1][j], dp[i][j-1]).
 Step 6: Return dp[m][n] as the length of longest common subsequence.

Submitted Code :