πDay 3. Longest Common Subsequence π§
The problem can be found at the following link: Question Link
π‘ Problem Description:
Given two strings s1 and s2, return the length of their longest common subsequence (LCS). If there is no common subsequence, return 0.
A subsequence is a sequence that can be derived from the given string by deleting some or no elements without changing the order of the remaining elements. For example, "ABE" is a subsequence of "ABCDE".
π Example Walkthrough:
Example 1:
Input:
s1 = "ABCDGH", s2 = "AEDFHR"Output:
3Explanation:
The longest common subsequence of "ABCDGH" and "AEDFHR" is "ADH", which has a length of 3.
Example 2:
Input:
Output:
Explanation:
The longest common subsequence of "ABC" and "AC" is "AC", which has a length of 2.
Example 3:
Input:
Output:
Explanation:
The longest common subsequences of "XYZW" and "XYWZ" are "XYZ" and "XYW", both of length 3.
Constraints:
$(1 \leq \text{length}(s1), \text{length}(s2) \leq 10^3)$
Both
s1ands2contain only uppercase English letters.
π― My Approach:
Space-Optimized 1D DP
Key Idea
Use only two arrays (current and previous rows) to store LCS lengths for substrings.
The value at
dp[j]represents the LCS length ofs1[0..i-1]ands2[0..j-1].Only the previous row is needed to compute the current row, so space is reduced to O(M), where M is the length of the second string.
Algorithm Steps
Use two rolling 1D arrays (or one array with a few variables) to store only the previous row and current row.
Traverse the strings from
i = 1..nandj = 1..m:If
s1[i - 1] == s2[j - 1], we docurr[j] = prev[j - 1] + 1.Else,
curr[j] = max(prev[j], curr[j - 1]).
Swap
prevandcurrat the end of eachiiteration.The result is
prev[m], which is the length of LCS.
This approach is more space-efficient than the standard O(N * M) DP table because it only keeps two rows (or one row with updates).
π Time and Auxiliary Space Complexity
Expected Time Complexity:
O(N * M), whereNis the length ofs1andMis the length ofs2.Expected Auxiliary Space Complexity:
O(N), using the space-optimized approach (storing only one dimension).
π Solution Code
Code (C++)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated