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

The longest common subsequence (LCS) problem for three strings finds the maximum length of characters that appear in the same relative order across all three strings. This is an extension of the classic two-string LCS problem using dynamic programming.

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".

Algorithm Steps

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 (m + 1) x (n + 1) x (o + 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]

Implementation

Let us see the following implementation to get better understanding ?

class Solution:
    def solve(self, s1, s2, s3):
        m = len(s1)
        n = len(s2)
        o = len(s3)
        
        # Create 3D DP table
        dp = [[[0 for i in range(o + 1)] for j in range(n + 1)] for k in range(m + 1)]
        
        # Fill the DP table
        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]

# Test the solution
ob = Solution()
s1 = "ababchemxde"
s2 = "pyakcimde"
s3 = "oauctime"
print(ob.solve(s1, s2, s3))

The output of the above code is ?

4

How It Works

The algorithm uses a 3D dynamic programming table where dp[i][j][k] represents the LCS length for the first i characters of s1, first j characters of s2, and first k characters of s3.

When all three characters match, we increment the LCS length by 1. Otherwise, we take the maximum LCS length by excluding one character from any of the three strings.

Time and Space Complexity

  • Time Complexity: O(m × n × o) where m, n, o are the lengths of the three strings
  • Space Complexity: O(m × n × o) for the 3D DP table

Conclusion

The three-string LCS problem extends the classic two-string approach using 3D dynamic programming. The algorithm efficiently finds the maximum length of common subsequence across all three input strings with O(m×n×o) complexity.

Updated on: 2026-03-25T13:35:49+05:30

741 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements