- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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])

- if s1[i - 1], s2[j - 1], s3[k - 1] are same, then

- for k in range 1 to o, do

- for j in range 1 to n, do
- return dp[m, n, o]

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) 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))

"ababchemxde", "pyakcimde", "oauctime"

4

- Related Questions & Answers
- Program to find length of longest common subsequence in C++
- Program to find length of longest balanced subsequence in Python
- Program to find length of longest anagram subsequence in Python
- Program to find length of longest increasing subsequence in Python
- Program to find length of longest palindromic subsequence in Python
- Program to find length of longest circular increasing subsequence in python
- Program to find length of longest bitonic subsequence in C++
- Program to find out the length of longest palindromic subsequence using Python
- Program to find length of longest common substring in C++
- Program to find length of longest arithmetic subsequence of a given list in Python
- Program to find longest common prefix from list of strings in Python
- Longest Common Subsequence
- Program to find length of longest Fibonacci subsequence from a given list in Python
- Program to find length of longest alternating subsequence from a given list in Python
- C++ Program for Longest Common Subsequence

Advertisements