# Program to make target by removing from first or last and inserting again in Python

ProgrammingPythonServer Side Programming

Suppose we have two strings S and T and they are permutations of each other. Suppose there is an operation where we remove either the first or the last character in S and insert it anywhere in the string. Then find the minimum number of operations needed to convert S into T.

So, if the input is like s = "zyvxw" t = "vwxyz", then the output will be 3, as these operations are: Remove "w" and insert it after "v" to get "zyvwx" Remove "z" and insert it after "x" to get "yvwxz" Remove "y" and insert it after "x" to get "vwxyz".

To solve this, we will follow these steps −

• ans := size of s, n := size of s

• for i in range 0 to n-1, do

• k := 0

• for j in range i to n-1, do

• for k in range k to size of t, do

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

• ans := minimum of ans and n - (j - i + 1)

• come out from the loop

• k := k + 1

• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

class Solution:
def solve(self, s, t):
ans = n = len(s)

for i in range(n):
k = 0
for j in range(i, n):
for k in range(k, len(t)):
if s[j] == t[k]:
ans = min(ans, n - (j - i + 1))
break
k += 1

return ans

ob = Solution()
s = "zyvxw"
t = "vwxyz"
print(ob.solve(s, t))

## Input

"zyvxw", "vwxyz"

## Output

5