Program to find length of longest common subsequence of three strings in Python


Suppose we have three strings s1, s2, and s3, we have to find the length of their longest common subsequence.

So, if the input is like s1 = "ababchemxde" s2 = "pyakcimde" s3 = "oauctime", then the output will be 4, as the longest common subsequence is "acme".

To solve this, we will follow these steps −

  • m := size of s1, n := size of s2, o := size of s3
  • dp := a 3D matrix of size (o + 1) x (n + 1) x (m + 1)
  • for i in range 1 to m, do
    • for j in range 1 to n, do
      • for k in range 1 to o, do
        • if s1[i - 1], s2[j - 1], s3[k - 1] are same, then
          • dp[i, j, k] := 1 + dp[i - 1, j - 1, k - 1]
        • otherwise,
          • dp[i, j, k] = maximum of (dp[i - 1, j, k], dp[i, j - 1, k] and dp[i,j, k - 1])
  • return dp[m, n, o]

Example (Python)

Let us see the following implementation to get better understanding −

 Live Demo

class Solution:
   def solve(self, s1, s2, s3):
      m = len(s1)
      n = len(s2)
      o = len(s3)
      dp = [[[0 for i in range(o + 1)] for j in range(n + 1)] for k in range(m + 1)]
      for i in range(1, m + 1):
         for j in range(1, n + 1):
            for k in range(1, o + 1):
               if s1[i - 1] == s2[j - 1] == s3[k - 1]:
                  dp[i][j][k] = 1 + dp[i - 1][j - 1][k - 1]
               else:
                  dp[i][j][k] = max(dp[i - 1][j][k], dp[i][j - 1][k], dp[i][j][k - 1])
         return dp[m][n][o]
ob = Solution()
s1 = "ababchemxde"
s2 = "pyakcimde"
s3 = "oauctime"
print(ob.solve(s1, s2, s3))

Input

"ababchemxde", "pyakcimde", "oauctime"

Output

4

Updated on: 12-Dec-2020

547 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements