Solution: Longest Common Subsequence of Three Sequences

Solution for the Longest Common Subsequence of Three Sequences Problem.

We'll cover the following


Let LCS(i,j,k)LCS(i,j,k) be the maximum length of a common subsequence of A[1i],B[1j],A[1\ldots i], B[1\ldots j], and C[1k]C[1\ldots k]. Then,

LCS(i,j,k)=max{LCS(i1,j,k)LCS(i,j1,k)LCS(i,j,k1)LCS(i1,j1,k1)+1if   A[i]=B[j]=C[k]LCS(i , j, k) = \text{max} \begin{cases} LCS(i-1 , j, k) \\ LCS(i , j-1, k) \\ LCS(i , j, k-1) \\ LCS(i-1, j-1, k-1)+1 & \text{if }~~ A[i]=B[j]=C[k] \end{cases}

Base case:

LCS(0,j,k)=LCS(i,0,k)=LCS(i,j,0)=0.LCS(0,j,k) = LCS(i,0,k) = LCS(i,j,0) = 0.

The corresponding algorithm has running time O(nmk)O(nmk).


Here is the code for the algorithm discussed above.

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.