# Program to find length of subsequence that can be removed still t is subsequence of s in Python

Suppose we have a string s and another string t. And t is a subsequence of s. We have to find the maximum length of a substring that we can remove from s so that, t is still a subsequence of s.

So, if the input is like s = "xyzxyxz" t = "yz", then the output will be 4, as We can remove the substring "abca"

To solve this, we will follow these steps −

• left := a new list, right := also a new list

• c1 := -1, c2 := -1, c3 := -1

• j := 0

• for i in range 0 to size of s, do

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

• insert i at the end of left

• j := j + 1

• if j is same as size of t , then

• c1 := size of s - i - 1

• come out from the loop

• j := size of t - 1

• for i in range size of s - 1 to 0, decrease by 1, do

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

• insert i into right at position 0

• j := j - 1

• if j is same as -1, then

• c2 := i

• come out from the loop

• for i in range 0 to size of t - 1, do

• c3 := maximum of c3 and (right[i + 1] - left[i] - 1)

• return maximum of c1, c2 and c3

## Example (Python)

Let us see the following implementation to get a better understanding −

Live Demo

class Solution:
def solve(self, s, t):
left = []
right = []
c1 = -1
c2 = -1
c3 = -1
j = 0
for i in range(len(s)):
if s[i] == t[j]:
left.append(i)
j += 1
if j == len(t):
c1 = len(s) - i - 1
break
j = len(t) - 1
for i in range(len(s) - 1, -1, -1):
if s[i] == t[j]:
right.insert(0, i)
j -= 1
if j == -1:
c2 = i
break
for i in range(len(t) - 1):
c3 = max(c3, right[i + 1] - left[i] - 1)
return max(c1, c2, c3)
ob = Solution()
s = "xyzxyxz"
t = "yz"
print(ob.solve(s, t))

## Input

"xyzxyxz", "yz"

## Output

4

Updated on: 22-Dec-2020

91 Views

##### Kickstart Your Career

Get certified by completing the course