Problem
Given three sequences A = $(a_1, a_2, \ldots, a_n)$ , B = $(b_1, b_2, \ldots, b_m)$, and C = $(c_1, c_2, \ldots, c_l)$, find the length of their longest common subsequence.
Examples
Example 1:
|
|
Solution
Method 1 - DP
To solve this problem, we will use a dynamic programming approach similar to the classic longest common subsequence problem, but extended to three sequences.
Steps
- Define a 3D DP Table:
- Let
dp[i][j][k]
represent the length of the longest common subsequence of the firsti
elements of ( a ), the firstj
elements of ( b ), and the firstk
elements of ( c ).
- Let
- Initialize the DP Table:
- Initialize
dp[0][x][y] = 0
,dp[x][0][y] = 0
, anddp[x][y][0] = 0
for all validx
andy
.
- Initialize
- Fill the DP Table:
- Iterate through all elements of ( a ), ( b ), and ( c ). For each
i
,j
, andk
:- If
a[i-1]
,b[j-1]
, andc[k-1]
are equal, thendp[i][j][k] = dp[i-1][j-1][k-1] + 1
. - Otherwise, take the maximum of excluding one element from either
a
,b
, orc
.
- If
- Iterate through all elements of ( a ), ( b ), and ( c ). For each
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n * m * l)
, wheren
,m
, andl
are the lengths of the sequences ( a ), ( b ), and ( c ) respectively. This is because we fill a 3D DP table. - 🧺 Space complexity:
O(n * m * l)
, due to storing the DP table.