Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Minimum number of given Operations Required to Convert a String to Another String
You are given two strings A and B, the task is to convert string A to string B using only one operation: taking any character from A and inserting it at the front. We need to find the minimum number of such operations required for transformation.
Problem Understanding
The key insight is that we can only move characters from their current position to the front of the string. This means we need to work backwards and check which characters are already in the correct relative order.
Example 1
For strings A = "ABD" and B = "BAD", we need 1 operation ?
A = "ABD"
B = "BAD"
# Move 'B' to front: ABD ? BAD
print(f"A: {A}")
print(f"B: {B}")
print("Operations needed: 1")
A: ABD B: BAD Operations needed: 1
Example 2
For strings A = "EACBD" and B = "EABCD", we need 3 operations ?
A = "EACBD"
B = "EABCD"
print("Step-by-step transformation:")
print(f"Original: {A}")
print("1. Move 'C' to front: EACBD ? CEABD")
print("2. Move 'B' to front: CEABD ? BCEABD ? BEACD")
print("3. Move 'A' to front: BEACD ? ABECD")
print("4. Move 'E' to front: ABECD ? EABCD")
print(f"Final: {B}")
print("Operations needed: 3")
Step-by-step transformation: Original: EACBD 1. Move 'C' to front: EACBD ? CEABD 2. Move 'B' to front: CEABD ? BCEABD ? BEACD 3. Move 'A' to front: BEACD ? ABECD 4. Move 'E' to front: ABECD ? EABCD Final: EABCD Operations needed: 3
Algorithm Approach
We traverse both strings from right to left, counting characters that are not in their final positions ?
def min_operations(A, B):
# Check if transformation is possible
if len(A) != len(B) or sorted(A) != sorted(B):
return -1
count = 0
i = len(A) - 1 # Pointer for string A
j = len(B) - 1 # Pointer for string B
# Traverse from right to left
while i >= 0 and j >= 0:
if A[i] == B[j]:
# Characters match, move both pointers
i -= 1
j -= 1
else:
# Character needs to be moved, increment count
count += 1
i -= 1
return count
# Test with examples
A1, B1 = "ABD", "BAD"
A2, B2 = "EACBD", "EABCD"
print(f"A='{A1}', B='{B1}' ? Operations: {min_operations(A1, B1)}")
print(f"A='{A2}', B='{B2}' ? Operations: {min_operations(A2, B2)}")
# Test impossible case
A3, B3 = "ABC", "XYZ"
print(f"A='{A3}', B='{B3}' ? Operations: {min_operations(A3, B3)}")
A='ABD', B='BAD' ? Operations: 1 A='EACBD', B='EABCD' ? Operations: 3 A='ABC', B='XYZ' ? Operations: -1
How It Works
The algorithm works by identifying the longest common suffix between A and B. Characters that are already in correct relative positions don't need to be moved ?
def explain_algorithm(A, B):
print(f"String A: {A}")
print(f"String B: {B}")
print("\nTraversing from right to left:")
i, j = len(A) - 1, len(B) - 1
operations = 0
while i >= 0 and j >= 0:
print(f"Comparing A[{i}]='{A[i]}' with B[{j}]='{B[j]}'")
if A[i] == B[j]:
print(f" Match! Both characters stay in place")
i -= 1
j -= 1
else:
print(f" No match! A[{i}]='{A[i]}' needs to move to front")
operations += 1
i -= 1
print(f"\nTotal operations needed: {operations}")
return operations
explain_algorithm("EACBD", "EABCD")
String A: EACBD String B: EABCD Traversing from right to left: Comparing A[4]='D' with B[4]='D' Match! Both characters stay in place Comparing A[3]='B' with B[3]='C' No match! A[3]='B' needs to move to front Comparing A[2]='C' with B[3]='C' Match! Both characters stay in place Comparing A[1]='A' with B[2]='B' No match! A[1]='A' needs to move to front Comparing A[0]='E' with B[2]='B' No match! A[0]='E' needs to move to front Total operations needed: 3
Complete Solution
def transform_string(A, B):
"""
Find minimum operations to convert string A to B
by moving characters to the front.
Returns -1 if conversion is impossible.
"""
# Check if transformation is possible
if len(A) != len(B):
return -1
if sorted(A) != sorted(B):
return -1
operations = 0
i = len(A) - 1
j = len(B) - 1
while i >= 0 and j >= 0:
if A[i] == B[j]:
i -= 1
j -= 1
else:
operations += 1
i -= 1
return operations
# Test cases
test_cases = [
("ABD", "BAD"),
("EACBD", "EABCD"),
("ABC", "CBA"),
("HELLO", "LLOHE"),
("ABC", "XYZ") # Impossible case
]
for A, B in test_cases:
result = transform_string(A, B)
print(f"'{A}' ? '{B}': {result} operations")
'ABD' ? 'BAD': 1 operations 'EACBD' ? 'EABCD': 3 operations 'ABC' ? 'CBA': 2 operations 'HELLO' ? 'LLOHE': 3 operations 'ABC' ? 'XYZ': -1 operations
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Single pass through both strings |
| Space | O(1) | Only using a few variables |
Conclusion
The algorithm efficiently finds the minimum operations by working backwards and counting characters that need repositioning. It runs in linear time and uses constant space, making it optimal for this problem.
