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 from string A to string B, if possible. You are allowed to perform only one operation that is to put any character from A and insert it at front. Check if it’s possible to convert the string. If yes, then output minimum number of operations required for transformation.

Input output Scenarios

Assume we have two strings A and B with values "ABD" and "BAD" respectively the operation need to take to convert the first string to the latter is 1 which is swapping the first two characters.

Input

A = "ABD", B = "BAD"

Output

1

Consider another scenario

Input

A = "EACBD", B = "EABCD"

Output

3

The operations need to convert A to B is

  • Take B and put at front, EACBD => BEACD

  • Take A and put at front, BEACD => ABECD

  • Take E and put at front, ABECD => EABCD

Python Implementation

Following is the implementation in Python

Example

def transformString(A, B):
    if len(A) != len(B):
        return -1    
    count = 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:
            count += 1
            i -= 1    
    return count
A = "Hello Welcome to Tutorialspoint    "
B = "Tutorialspoint simply easy learning"
print("Operations Required: ", transformString(A, B))  

A = "EACBD"
B = "EABCD"
print("Operations Required: ", transformString(A, B)) 

Output

Operations Required:  35
Operations Required:  3

Approach

Let us understand the approach followed by debugging the above program

  • The function initially determines whether the lengths of A and B are equal. The function returns −1 if they don't since it is impossible to change A into B by adding letters at the beginning.

  • When A and B are both the same length, the function initializes two pointers, i and j, that point to the ends of A and B, respectively, and a variable count to 0.

  • After that, the function begins a while loop, which continues to execute as long as i and j are both non−negative.

  • Within the while loop, the function checks whether the character at A[i] is equal to the character at B[j]. If they are equal, the function decrements both i and j by 1, effectively skipping over those characters.

  • If the characters are not equal, the function increments count by 1 and decrements i by 1, effectively "inserting" the character at A[i] at the front of A.

  • The function then determines whether j is negative following the while loop's termination. If it is, all of the characters in B have been matched with their equivalents in A, and the value of count reflects the bare minimum of insertions needed to change A into B. The function gives back a count.

  • It is impossible to change A to B by adding characters at the front if j is not negative since B still contains unmatched characters. When conversion is not possible, the function returns −1.

Java Implementation

Java Implementation of the above code

Example

import java.util.*;

public class Demo{
   public static int transformString(String A, String B) {
   if (A.length() != B.length()) {
      return -1;
   }
   int count = 0;
   int i = A.length() - 1;
   int j = B.length() - 1;

   while (i >= 0 && j >= 0) {
      if (A.charAt(i) == B.charAt(j)) {
         i--;
         j--;
      } else {
         count++;
         i--;
      }
   }
      return count;
   }

   public static void main(String[] args) {
      String A = "Hello Welcome to Tutorialspoint    ";
      String B = "Tutorialspoint simply easy learning";
      int result = transformString(A, B);
      System.out.println("Minimum number of operations required: " + result);

      A = "EACBD";
      B = "EABCD";
      result = transformString(A, B);
      System.out.println("Minimum number of operations required: " + result);
   }
}

Output

Minimum number of operations required: 35
Minimum number of operations required: 3

Time and Space Complexity

The transform function has an O(n) time complexity, where n is the length of the input strings A and B. This is so that the function, which uses the two pointers i and j to loop through the characters of the strings from end to beginning, can compare characters and increase or decrement the pointers and count at regular intervals. The temporal complexity is therefore proportional to the length of the strings.

The transform function has an O(1) space complexity, thus the amount of extra memory it requires is independent of the length of the input strings. The function does not generate any additional data structures or dynamically allocate memory; it just needs a fixed amount of memory to store the variables count, i, and j.

Updated on: 22-Aug-2023

304 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements