Program to find length of shortest supersequence in Python


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]

Example 

Let us see the following implementation to get better understanding −

 Live Demo

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

Input

"pipe", "people"

Output

7

Updated on: 22-Dec-2020

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements