- Related Questions & Answers
- Python program to interchange first and last elements in a list
- Removing duplicates and inserting empty strings in JavaScript
- Program to remove last occurrence of a given target from a linked list in Python
- Find longest palindrome formed by removing or shuffling chars from string in Python
- Program to find maximum sum by removing K numbers from ends in python
- Find sum by removing first character from a string followed by numbers in MySQL?
- Program to find intervals by merging target interval in Python
- Program to find how max score we can get by removing 10 or 01 from binary string in Python
- Python Program to Swap the First and Last Value of a List
- Get first and last elements from Java LinkedList
- MySQL GROUP BY and CONCAT() to display distinct first and last name
- Get first and last elements from Vector in Java
- How to get first and last elements from ArrayList in Java?
- Removing first k characters from string in JavaScript
- Program to find a sublist where first and last values are same in Python

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

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

"zyvxw", "vwxyz"

5

Advertisements