Leetcode 1143: Longest Common Subsequence

grid47
grid47
Exploring patterns and algorithms
Jul 15, 2024 5 min read

Given two strings text1 and text2, return the length of their longest common subsequence. A subsequence is a sequence that can be derived from the string by deleting some characters without changing the order of the remaining characters.
Problem
Approach
Steps
Complexity
Input: You are given two strings text1 and text2. The characters in each string are lowercase English letters.
Example: Input: text1 = 'apple', text2 = 'applause'
Constraints:
• 1 <= text1.length, text2.length <= 1000
• text1 and text2 consist of only lowercase English characters.
Output: Return the length of the longest common subsequence between text1 and text2.
Example: Output: 5
Constraints:
• The output will be a single integer representing the length of the longest common subsequence.
Goal: Find the length of the longest common subsequence by comparing characters of both strings and using dynamic programming to store the results of overlapping subproblems.
Steps:
• 1. Create a 2D DP table to store the lengths of longest common subsequences for different substrings.
• 2. Iterate through both strings. If characters match, add 1 to the value of the previous common subsequence.
• 3. If characters do not match, take the maximum length from either of the previous two subsequences.
• 4. The final value in the DP table will be the length of the longest common subsequence.
Goal: The problem must be solved efficiently with respect to both time and space complexity.
Steps:
• 1 <= text1.length, text2.length <= 1000
• 1 <= text2.length <= 1000
Assumptions:
• Both text1 and text2 will consist only of lowercase English characters.
• The length of both text1 and text2 will be between 1 and 1000.
Input: Input: text1 = 'apple', text2 = 'applause'
Explanation: In this example, the longest common subsequence between 'apple' and 'applause' is 'apple', which has a length of 5.

Input: Input: text1 = 'happy', text2 = 'sad'
Explanation: In this example, the longest common subsequence between 'happy' and 'sad' is 'a', which has a length of 1.

Input: Input: text1 = 'cat', text2 = 'dog'
Explanation: In this example, there is no common subsequence between 'cat' and 'dog', so the result is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus