- 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 two strings s and t. We have to find the length of the shortest string that has both s and t as subsequences.

So, if the input is like s = "pipe" t = "people", then the output will be 7, as one possible supersequence is "pieople".

To solve this, we will follow these steps −

m := size of s, n := size of t

table := a table of size (n + 1) x (m + 1) and fill with 0

for i in range 0 to m, do

for j in range 0 to n, do

if i is same as 0 or j is same as 0, then

table[i, j] := 0

otherwise,

if s[i - 1] is same as t[j - 1], then

table[i, j] := 1 + table[i - 1, j - 1]

otherwise,

table[i, j] = maximum of table[i, j - 1] and table[i - 1, j]

return m + n - table[m, n]

Let us see the following implementation to get better understanding −

class Solution: def solve(self, s, t): m = len(s) n = len(t) table = [[0 for i in range(n + 1)] for j in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0 or j == 0: table[i][j] = 0 else: if s[i - 1] == t[j - 1]: table[i][j] = 1 + table[i - 1][j - 1] else: table[i][j] = max(table[i][j - 1], table[i - 1][j]) return m + n - table[m][n] ob = Solution() s = "pipe" t = "people" print(ob.solve(s, t))

"pipe", "people"

7

- Related Questions & Answers
- Shortest Common Supersequence in C++
- Program to find shortest cycle length holding target in python
- C++ Program to Find the Shortest Supersequence that Contains Two or more Sequences as Subsequences
- Program to find length of shortest sublist with maximum frequent element with same frequency in Python
- Program to find length of longest matrix path length in Python
- Program to find distance of shortest bridge between islands in Python
- Program to find maximum length of k ribbons of same length in Python
- Program to find minimum length of lossy Run-Length Encoding in Python
- Length of shortest unsorted array in JavaScript
- Python - Filter Supersequence Strings
- 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 consecutive sequence in Python
- Program to find length of longest distinct sublist in Python
- Program to find length of longest increasing subsequence in Python

Advertisements