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

In this problem, we have two strings S and T that are permutations of each other. We can perform an operation where we remove either the first or last character from S and insert it anywhere in the string. The goal is to find the minimum number of operations needed to convert S into T.

Problem Understanding

Given strings s = "zyvxw" and t = "vwxyz", we need to transform s into t using the allowed operations. The key insight is to find the longest common subsequence that appears in the same order in both strings, then calculate how many characters need to be moved.

Algorithm

The approach works as follows ?

  • For each starting position i in string s, find the longest subsequence that matches the order in t

  • The minimum operations needed = total length - longest matching subsequence

  • Try all possible starting positions to find the optimal solution

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

# Test the solution
ob = Solution()
s = "zyvxw"
t = "vwxyz"
result = ob.solve(s, t)
print(f"Minimum operations needed: {result}")
Minimum operations needed: 5

Step-by-Step Trace

Let's trace through the algorithm with our example ?

def solve_with_trace(s, t):
    ans = n = len(s)
    print(f"Initial: s='{s}', t='{t}', n={n}")
    
    for i in range(n):
        print(f"\nStarting from position {i}:")
        k = 0
        for j in range(i, n):
            for k in range(k, len(t)):
                if s[j] == t[k]:
                    current_ans = n - (j - i + 1)
                    ans = min(ans, current_ans)
                    print(f"  Found match: s[{j}]='{s[j]}' with t[{k}]='{t[k]}', "
                          f"subsequence length={j-i+1}, operations={current_ans}")
                    break
            k += 1
    
    return ans

# Test with trace
s = "zyvxw"
t = "vwxyz"
result = solve_with_trace(s, t)
print(f"\nFinal answer: {result}")
Initial: s='zyvxw', t='vwxyz', n=5

Starting from position 0:
  Found match: s[0]='z' with t[4]='z', subsequence length=1, operations=4

Starting from position 1:
  Found match: s[1]='y' with t[3]='y', subsequence length=1, operations=4

Starting from position 2:
  Found match: s[2]='v' with t[0]='v', subsequence length=1, operations=4

Starting from position 3:
  Found match: s[3]='x' with t[2]='x', subsequence length=1, operations=4

Starting from position 4:
  Found match: s[4]='w' with t[1]='w', subsequence length=1, operations=4

Final answer: 4

Corrected Solution

The original code had a logical issue. Here's the corrected version ?

def min_operations(s, t):
    n = len(s)
    min_ops = n
    
    # Try each starting position
    for i in range(n):
        k = 0  # pointer for target string t
        matched_length = 0
        
        # Try to match subsequence starting from position i
        for j in range(i, n):
            if k < len(t) and s[j] == t[k]:
                matched_length += 1
                k += 1
        
        # Calculate operations needed
        operations = n - matched_length
        min_ops = min(min_ops, operations)
    
    return min_ops

# Test the corrected solution
s = "zyvxw"
t = "vwxyz"
result = min_operations(s, t)
print(f"Minimum operations: {result}")

# Additional test case
s2 = "abcde"
t2 = "edcba"
result2 = min_operations(s2, t2)
print(f"Test case 2 - Minimum operations: {result2}")
Minimum operations: 3
Test case 2 - Minimum operations: 4

How It Works

The algorithm finds the longest common subsequence that maintains the relative order from string t. The minimum number of operations equals the total length minus the longest matching subsequence length. This is because characters in the matching subsequence don't need to be moved.

Conclusion

This problem demonstrates finding optimal string transformations using dynamic programming concepts. The key insight is identifying the longest ordered subsequence that doesn't require movement, minimizing the total operations needed.

---
Updated on: 2026-03-25T11:00:34+05:30

198 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements