04. LCS of three Strings
โ GFG solution for LCS of 3 strings: dynamic programming with full 3D table, space optimized 2D, and recursion with memoization. ๐ก
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given three strings A, B, and C, the task is to find the length of the Longest Common Subsequence (LCS) present in all three strings.
A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous.
๐ Examples
Example 1
Input:
s1 = "geeks"
s2 = "geeksfor"
s3 = "geeksforgeeks"
Output: 5
Explanation:
The longest common subsequence is "geeks" (length = 5).Example 2
๐ Constraints
$1 \leq |s1|,|s2|,|s3| \leq 100$
Strings contain only lowercase English letters.
โ
My Approach
Optimized 2D DP (Rolling Arrays)
Idea:
A naive 3D DP table $dp[i][j][k]$ (size $(n1+1) \times (n2+1) \times (n3+1)$) takes $O(n1 \times n2 \times n3)$ time and space.
We can reduce space by noticing that at layer
i, we only need layeri-1to compute the current values.Maintain two 2D arrays
prev[j][k]andcurr[j][k]of size $(n2+1) \times (n3+1)$.
DP Relation:
Let
n1 = |s1|,n2 = |s2|,n3 = |s3|.For each
ifrom1ton1, and for eachjfrom1ton2, and eachkfrom1ton3:If
s1[i-1] == s2[j-1] == s3[k-1], thencurr[j][k]=1+prev[jโ1][kโ1];Otherwise,
curr[j][k]=max(prev[j][k],curr[jโ1][k],curr[j][kโ1]).
After filling
currfor a fixedi, swapprevandcurr, and zero outcurrfor the next iteration.
Answer:
The value
prev[n2][n3]at the end of the loops is the length of the LCS among all three strings.
๐ Time and Auxiliary Space Complexity
Expected Time Complexity: $\displaystyle O(n1 \times n2 \times n3)$, since we iterate over all
i โ [1..n1],j โ [1..n2],k โ [1..n3].Expected Auxiliary Space Complexity: $\displaystyle O(n2 \times n3)$, because we only store two 2D arrays of size $(n2+1)\times(n3+1)$ instead of a full 3D table.
๐งโ๐ป Code (C++)
โก View Alternative Approaches with Code and Analysis
๐ 2๏ธโฃ Full 3D DP Table
Algorithm Steps:
Define a 3D DP array:
dp[i][j][k]=lengthย ofย LCSย forย s1[0..iโ1],s2[0..jโ1],s3[0..kโ1].Initialize a
(n1+1) ร (n2+1) ร (n3+1)table with zeros.For each
iin[1..n1],jin[1..n2],kin[1..n3]:If
s1[i-1] == s2[j-1] == s3[k-1], thendp[i][j][k]=1+dp[iโ1][jโ1][kโ1];Otherwise,
dp[i][j][k]=max(dp[iโ1][j][k],dp[i][jโ1][k],dp[i][j][kโ1]).
Return
dp[n1][n2][n3].
๐ Complexity Analysis:
Time: โฑ๏ธ O(n1 ร n2 ร n3) โ three nested loops.
Auxiliary Space: ๐พ O(n1 ร n2 ร n3) โ full 3D DP table.
โ
Why This Approach?
Directly generalizes 2-string LCS to three dimensions.
Conceptually straightforwardโeach state references the previous layer for matching or skipping.
๐ 3๏ธโฃ Recursive + Memoization
Algorithm Steps:
Define a recursive function
solve(i, j, k)that returns LCS length up to indicesi,j,k(0-based).Base case: if any of
i,j, orkis< 0, return 0.Use a 3D memo table
memo[i][j][k], initialized to-1.If
s1[i] == s2[j] == s3[k], thenmemo[i][j][k]=1+solve(iโ1,jโ1,kโ1);Otherwise,
memo[i][j][k]=max(solve(iโ1,j,k),solve(i,jโ1,k),solve(i,j,kโ1)).Return
memo[n1-1][n2-1][n3-1].
๐ Complexity Analysis:
Time: โฑ๏ธ O(n1 ร n2 ร n3) โ each
(i,j,k)computed once via memo.Auxiliary Space: ๐พ O(n1 ร n2 ร n3) โ memo table plus recursion stack.
โ
Why This Approach?
Expresses the problem in a recursive decision-tree style.
Memoization avoids redundant computations of overlapping subproblems.
๐ ๐ Comparison of Approaches
๐ Approach
โฑ๏ธ Time Complexity
๐พ Space Complexity
โ Pros
โ ๏ธ Cons
๐ฏ 2D DP + Swap (Optimized)
๐ข O(n1 ร n2 ร n3)
๐ข O(n2 ร n3)
Low memory (only two 2D layers), easy to implement
Still O(n1ยทn2ยทn3) runtime
๐งฎ Full 3D DP Table
๐ข O(n1 ร n2 ร n3)
๐ด O(n1 ร n2 ร n3)
Conceptually simple 3D extension
Very high memory usage for large inputs
๐ Recursive + Memoization
๐ข O(n1 ร n2 ร n3)
๐ด O(n1 ร n2 ร n3) (stack)
Clear recursion logic, easy to reason
Large recursion depth; high memory overhead
๐ Best Choice by Scenario
๐ฏ Scenario
๐ฅ Recommended Approach
๐ Moderate lengths where memory matters (n1ยทn2ยทn3 large)
๐ฅ Optimized 2D DP + Swap
๐ Educational or small inputs, prioritize clarity
๐ฅ Full 3D DP Table
๐ก Recursive style or quick prototyping, small to medium sizes
๐ฅ Recursive + Memoization
๐งโ๐ป 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