

- 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
Program to make target by removing from first or last and inserting again in Python
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
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
- Related Questions & Answers
- Program to find number of operations needed to make pairs from first and last side are with same sum in Python
- Program to check first player can win by reaching total sum to target in Python
- Removing duplicates and inserting empty strings in JavaScript
- Python program to interchange first and last elements in a list
- 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?
- Java Program to Get First and Last Elements from an Array List
- Program to find number of restricted paths from first to last node in Python
- Program to find how max score we can get by removing 10 or 01 from binary string in Python
- Program to find intervals by merging target interval in Python
- Get first and last elements from Java LinkedList
- Python Program to Swap the First and Last Value of a List
- Get first and last elements from Vector in Java