
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)
Editorial
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. |
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.