Longest Common Subsequence
Logical Breakdown
- [ ] Subproblem Identification:
- [ ] Optimal Substructure:
- [ ] Constraint Handling: (e.g., Modulo \(10^9 + 7\))
- [ ] Optimization: (Matrix Exponentiation if 'A' is huge)
Mathematical Rigor
State Definition
Let \(dp[i]\) be the state for the \(i\)-th subproblem.
Recurrence Relation
Visualization
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Iterative DP | \(O(N)\) | \(O(1)\) |
Code Reference
package com.dsa.dynamic_programming;
import java.util.*;
/ * Problem: Longest Common Subsequence * Group: 11. Dynamic Programming */ / * ============================================================================================ * PROBLEM: Longest Common Subsequence * ============================================================================================ * * --------------------- * 1. Problem Description * --------------------- * Given two strings A and B. Find the length of the longest common subsequence (LCS). * A subsequence is a sequence that can be derived from another string by deleting some * or no characters without changing the order of the remaining characters. * * --------------------- * 2. Logical Breakdown & Mathematical Formulation * --------------------- * Let dp[i][j] be the LCS length of substring A[0...i-1] and B[0...j-1]. * * Recurrence Relation: * We compare the last characters A[i-1] and B[j-1]: * 1. If A[i-1] == B[j-1]: * The character matches. We add 1 to the result of the prefix. * dp[i][j] = 1 + dp[i-1][j-1] * * 2. If A[i-1] != B[j-1]: * We cannot include both characters. We must skip one from either A or B. * dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]) * * Base Case: * dp[0][j] = 0 (Empty string A has no common subsequence) * dp[i][0] = 0 (Empty string B has no common subsequence) * * --------------------- * 3. Complexity * --------------------- * Time: O(N * M) * Space: O(N * M) * * ============================================================================================ */ public class LongestCommonSubsequence { public int solve(int A) { // TODO: Implement solution return 0; }
public int solveLCS(String abcde, String ace) {
return 1;
}
}