Transform One String to Another using Minimum Number of Given Operation
Last Updated :
05 Dec, 2024
Given two strings A and B, the task is to convert A to B if possible. The only operation allowed is to put any character from A and insert it at front. Find if it's possible to convert the string. If yes, then output minimum no. of operations required for transformation.
Examples:
Input: A = "ABD", B = "BAD"
Output: 1
Explanation: Pick B and insert it at front.
Input: A = "EACBD", B = "EABCD"
Output: 3
Explanation: Pick B and insert at front, EACBD => BEACD
Pick A and insert at front, BEACD => ABECD
Pick E and insert at front, ABECD => EABCD
BRUTE METHOD: (Using HashMap)
Algorithm:
- We declare a HashMap<Character,Integer> to store frequency map.
- We store the character of string 1 in the map and then while traversing string 2 ,we erase the characters and if the map is empty at the end that means the characters in both the string are same and we can continue,else we return -1.
- We make a variable res and point two pointer i and j to the last of both strings and start traversing from back.
- As soon as see a ith character that doesn't match with jth character ,we start increasing res by 1 until again both the characters are same.
- Atlast we return res.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int transform(string A, string B)
{
if (A.length() != B.length()) {
return -1;
}
// create a map to store the frequency of characters in string A
unordered_map<char, int> m;
int n = A.length();
for (int i = 0; i < n; i++) {
if (m.count(A[i])) // if the character already exists in the map
m[A[i]]++; // increment its frequency
else
m[A[i]] = 1; // add the character to the map with a frequency of 1
}
// subtract the frequency of characters in string B from the map
for (int i = 0; i < n; i++) {
if (m.count(B[i]))
m[B[i]]--;
}
// check if all the frequencies in the map are 0, indicating equal frequency of characters in both strings
for (auto it : m) {
if (it.second != 0) // if frequency is not zero
return -1; // strings cannot be transformed into each other, return -1
}
// calculate the minimum number of operations required to transform string A into string B
int i = n - 1, j = n - 1;
int res = 0;
while (i >= 0 && j >= 0) {
while (i >= 0 && A[i] != B[j]) {
res++; // increment the number of operations required
i--; // move the pointer i to the left
}
i--;
j--;
}
return res; // returning result
}
// Driver code
int main()
{
string A = "EACBD";
string B = "EABCD";
cout << "Minimum number of operations required is " << transform(A, B) << endl;
return 0;
}
Java
// Java proram to transform the string
import java.io.*;
import java.util.*;
class GFG {
public static int transform(String A, String B)
{
// code here
if (A.length() != B.length()) {
return -1;
}
HashMap<Character, Integer> m
= new HashMap<Character, Integer>();
int n = A.length();
for (int i = 0; i < n; i++) {
if (m.containsKey(A.charAt(i)))
m.put(A.charAt(i), m.get(A.charAt(i)) + 1);
else
m.put(A.charAt(i), 1);
}
for (int i = 0; i < n; i++) {
if (m.containsKey(B.charAt(i)))
m.put(B.charAt(i), m.get(B.charAt(i)) - 1);
}
for (Map.Entry<Character, Integer> entry :
m.entrySet()) {
if (entry.getValue() != 0)
return -1;
}
int i = n - 1, j = n - 1;
int res = 0;
while (i >= 0 && j >= 0) {
while (i >= 0 && A.charAt(i) != B.charAt(j)) {
res++;
i--;
}
i--;
j--;
}
return res;
}
public static void main(String[] args)
{
String A = "EACBD";
String B = "EABCD";
System.out.println(
"Minimum number of operations required is "
+ transform(A, B));
}
}
// This code is contributed by Raunak Singh
Python
def transform(A, B):
if len(A) != len(B):
return -1
# create a dictionary to store the frequency of characters in string A
m = {}
n = len(A)
for i in range(n):
if A[i] in m: # if the character already exists in the dictionary
m[A[i]] += 1 # increment its frequency
else:
m[A[i]] = 1 # add the character to the dictionary with a frequency of 1
# subtract the frequency of characters in string B from the dictionary
for i in range(n):
if B[i] in m:
m[B[i]] -= 1
# check if all the frequencies in the dictionary are 0, indicating equal frequency of characters in both strings
for key in m:
if m[key] != 0: # if frequency is not zero
return -1 # strings cannot be transformed into each other, return -1
# calculate the minimum number of operations required to transform string A into string B
i, j = n-1, n-1
res = 0
while i >= 0 and j >= 0:
while i >= 0 and A[i] != B[j]:
res += 1 # increment the number of operations required
i -= 1 # move the pointer i to the left
i -= 1
j -= 1
return res # returning result
# Driver code
A = "EACBD"
B = "EABCD"
print("Minimum number of operations required is", transform(A, B))
C#
using System;
using System.Collections.Generic;
class GFG
{
public static int Transform(string A, string B)
{
if (A.Length != B.Length)
{
return -1;
}
// create a dictionary to store the frequency of characters in string A
Dictionary<char, int> m = new Dictionary<char, int>();
int n = A.Length;
for (int i = 0; i < n; i++)
{
if (m.ContainsKey(A[i])) // if the character already exists in the dictionary
{
m[A[i]]++; // increment its frequency
}
else
{
m[A[i]] = 1; // add the character to the dictionary with a frequency of 1
}
}
// subtract the frequency of characters in string B from the dictionary
for (int i = 0; i < n; i++)
{
if (m.ContainsKey(B[i]))
{
m[B[i]]--;
}
}
// check if all the frequencies in the dictionary are 0, indicating equal frequency of characters in both strings
foreach (var entry in m)
{
if (entry.Value != 0)
{
return -1;
}
}
// calculate the minimum number of operations required to transform string A into string B
int it = n - 1, j = n - 1;
int res = 0;
while (it >= 0 && j >= 0)
{
while (it >= 0 && A[it] != B[j])
{
res++;
it--;
}
it--;
j--;
}
return res;
}
// Driver code
public static void Main(string[] args)
{
string A = "EACBD";
string B = "EABCD";
Console.WriteLine("Minimum number of operations required is " + Transform(A, B));
}
}
JavaScript
function transform(A, B) {
if (A.length !== B.length) {
return -1;
}
// Create an object to store the frequency of characters in string A
const m = {};
const n = A.length;
for (let i = 0; i < n; i++) {
if (m[A[i]]) { // if the character already exists in the object
m[A[i]]++; // increment its frequency
} else {
m[A[i]] = 1; // add the character to the object with a frequency of 1
}
}
// Subtract the frequency of characters in string B from the object
for (let i = 0; i < n; i++) {
if (m[B[i]]) {
m[B[i]]--;
}
}
// Check if all the frequencies in the object are 0,
// indicating equal frequency of characters in both strings
for (const char in m) {
if (m[char] !== 0) { // if frequency is not zero
return -1; // strings cannot be transformed into each other, return -1
}
}
// Calculate the minimum number of operations
// required to transform string A into string B
let i = n - 1, j = n - 1;
let res = 0;
while (i >= 0 && j >= 0) {
while (i >= 0 && A[i] !== B[j]) {
res++; // increment the number of operations required
i--; // move the pointer i to the left
}
i--;
j--;
}
return res; // returning result
}
// Driver code
const A = "EACBD";
const B = "EABCD";
console.log("Minimum number of operations required is " + transform(A, B));
OutputMinimum number of operations required is 3
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Checking whether a string can be transformed to another is simple. We need to check whether both strings have same number of characters and same set of characters. This can be easily done by creating a count array for first string and checking if second string has same count of every character.
How to find minimum number of operations when we are sure that we can transform A to B? The idea is to start matching from last characters of both strings. If last characters match, then our task reduces to n-1 characters. If last characters don't match, then find the position of B's mismatching character in A. The difference between two positions indicates that these many characters of A must be moved before current character of A.
Below is complete algorithm.
1) Find if A can be transformed to B or not by first creating a count array for all characters of A, then checking with B if B has same count for every character.
2) Initialize result as 0.
3) Start traversing from end of both strings.
……a) If current characters of A and B match, i.e., A[i] == B[j]
………then do i = i-1 and j = j-1
b) If current characters don't match, then search B[j] in remaining
………A. While searching, keep incrementing result as these characters
………must be moved ahead for A to B transformation.
Below are the implementations based on this idea.
C++
// C++ program to find minimum number of operations required
// to transform one string to other
#include <bits/stdc++.h>
using namespace std;
// Function to find minimum number of operations required to
// transform A to B.
int minOps(string& A, string& B)
{
int m = A.length(), n = B.length();
// This parts checks whether conversion is possible or not
if (n != m)
return -1;
int count[256];
memset(count, 0, sizeof(count));
// count characters in A
for (int i = 0; i < n; i++)
count[A[i]]++;
// subtract count for every character in B
for (int i = 0; i < n; i++)
count[B[i]]--;
// Check if all counts become 0
for (int i = 0; i < 256; i++)
if (count[i])
return -1;
// This part calculates the number of operations
// required
int res = 0;
for (int i = n - 1, j = n - 1; i >= 0;) {
// If there is a mismatch, then keep incrementing
// result 'res' until B[j] is not found in A[0..i]
while (i >= 0 && A[i] != B[j]) {
i--;
res++;
}
// If A[i] and B[j] match
if (i >= 0) {
i--;
j--;
}
}
return res;
}
// Driver program
int main()
{
string A = "EACBD";
string B = "EABCD";
cout << "Minimum number of operations required is " << minOps(A, B);
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
C
// C program to find minimum number of operations required
// to transform one string to other
#include <stdio.h>
#include <string.h>
// Function to find minimum number of operations required to
// transform A to B.
int minOps(char A[], char B[])
{
int m = strlen(A), n = strlen(B);
// This parts checks whether conversion is
// possible or not
if (n != m)
return -1;
int count[256];
for (int i = 0; i < 256; i++)
count[i] = 0;
// count characters in A
for (int i = 0; i < n; i++)
count[A[i]]++;
// subtract count for every character in B
for (int i = 0; i < n; i++)
count[B[i]]--;
// Check if all counts become 0
for (int i = 0; i < 256; i++)
if (count[i])
return -1;
// This part calculates the number of operations
// required
int res = 0;
for (int i = n - 1, j = n - 1; i >= 0;) {
// If there is a mismatch, then keep incrementing
// result 'res' until B[j] is not found in A[0..i]
while (i >= 0 && A[i] != B[j]) {
i--;
res++;
}
// If A[i] and B[j] match
if (i >= 0) {
i--;
j--;
}
}
return res;
}
// Driver program
int main()
{
char A[] = "EACBD";
char B[] = "EABCD";
printf("Minimum number of operations required is %d", minOps(A, B));
return 0;
}
// This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program to find minimum number of operations
// required to transform one string to other
import java.io.*;
import java.util.*;
public class GFG {
// Function to find minimum number of operations
// required to transform A to B.
public static int minOps(String A, String B)
{
// This parts checks whether conversion is possible
// or not
if (A.length() != B.length())
return -1;
int i, j, res = 0;
int count[] = new int[256];
// count characters in A
// subtract count for every character in B
for (i = 0; i < A.length(); i++) {
count[A.charAt(i)]++;
count[B.charAt(i)]--;
}
// Check if all counts become 0
for (i = 0; i < 256; i++)
if (count[i] != 0)
return -1;
i = A.length() - 1;
j = B.length() - 1;
while (i >= 0) {
// If there is a mismatch, then keep
// incrementing result 'res' until B[j] is not
// found in A[0..i]
if (A.charAt(i) != B.charAt(j))
res++;
else
j--;
i--;
}
return res;
}
// Driver code
public static void main(String[] args)
{
String A = "EACBD";
String B = "EABCD";
System.out.println(
"Minimum number of operations required is "
+ minOps(A, B));
}
}
// This code is contributed by Aditya Kumar (adityakumar129)
Python
# Python program to find the minimum number of
# operations required to transform one string to other
# Function to find minimum number of operations required
# to transform A to B
def minOps(A, B):
m = len(A)
n = len(B)
# This part checks whether conversion is possible or not
if n != m:
return -1
count = [0] * 256
for i in range(n): # count characters in A
count[ord(B[i])] += 1
for i in range(n): # subtract count for every char in B
count[ord(A[i])] -= 1
for i in range(256): # Check if all counts become 0
if count[i]:
return -1
# This part calculates the number of operations required
res = 0
i = n-1
j = n-1
while i >= 0:
# if there is a mismatch, then keep incrementing
# result 'res' until B[j] is not found in A[0..i]
while i>= 0 and A[i] != B[j]:
i -= 1
res += 1
# if A[i] and B[j] match
if i >= 0:
i -= 1
j -= 1
return res
# Driver program
A = "EACBD"
B = "EABCD"
print ("Minimum number of operations required is " + str(minOps(A,B)))
# This code is contributed by Bhavya Jain
C#
// C# program to find minimum number of
// operations required to transform one
// string to other
using System;
class GFG
{
// Function to find minimum number of
// operations required to transform
// A to B.
public static int minOps(string A, string B)
{
// This parts checks whether
// conversion is possible or not
if (A.Length != B.Length)
{
return -1;
}
int i, j, res = 0;
int[] count = new int [256];
// count characters in A
// subtract count for every
// character in B
for (i = 0; i < A.Length; i++)
{
count[A[i]]++;
count[B[i]]--;
}
// Check if all counts become 0
for (i = 0; i < 256; i++)
{
if (count[i] != 0)
{
return -1;
}
}
i = A.Length - 1;
j = B.Length - 1;
while (i >= 0)
{
// If there is a mismatch, then
// keep incrementing result 'res'
// until B[j] is not found in A[0..i]
if (A[i] != B[j])
{
res++;
}
else
{
j--;
}
i--;
}
return res;
}
// Driver code
public static void Main(string[] args)
{
string A = "EACBD";
string B = "EABCD";
Console.WriteLine("Minimum number of " +
"operations required is " +
minOps(A, B));
}
}
// This code is contributed by Shrikant13
JavaScript
<script>
// Javascript program to find minimum number
// of operations required to transform one
// string to other
// Function to find minimum number of
// operations required to transform
// A to B.
function minOps(A, B)
{
// This parts checks whether conversion
// is possible or not
if (A.length != B.length)
return -1;
let i, j, res = 0;
let count = new Array(256);
for(let i = 0; i < 256; i++)
{
count[i] = 0;
}
// count characters in A
// Subtract count for every character in B
for(i = 0; i < A.length; i++)
{
count[A[i].charCodeAt(0)]++;
count[B[i].charCodeAt(0)]--;
}
// Check if all counts become 0
for(i = 0; i < 256; i++)
if (count[i] != 0)
return -1;
i = A.length - 1;
j = B.length - 1;
while(i >= 0)
{
// If there is a mismatch, then
// keep incrementing result 'res'
// until B[j] is not found in A[0..i]
if (A[i] != B[j])
res++;
else
j--;
i--;
}
return res;
}
// Driver code
let A = "EACBD";
let B = "EABCD";
document.write("Minimum number of " +
"operations required is " +
minOps(A, B));
// This code is contributed by avanitrachhadiya2155
</script>
PHP
<?php
// PHP program to find minimum number of
// operations required to transform one string to other
// Function to find minimum number of operations required to transform
// A to B.
function minOps($A, $B)
{
$m = strlen($A);
$n = strlen($B);
// This parts checks whether conversion is
// possible or not
if ($n != $m)
return -1;
$count = array_fill(0,256,NULL);
for ($i=0; $i<$n; $i++) // count characters in A
$count[ord($B[$i])]++;
for ($i=0; $i<$n; $i++) // subtract count for
$count[ord($A[$i])]--; // every character in B
for ($i=0; $i<256; $i++) // Check if all counts become 0
if ($count[$i])
return -1;
// This part calculates the number of operations required
$res = 0;
for ($i=$n-1, $j=$n-1; $i>=0; )
{
// If there is a mismatch, then keep incrementing
// result 'res' until B[j] is not found in A[0..i]
while ($i>=0 && $A[$i] != $B[$j])
{
$i--;
$res++;
}
// If A[i] and B[j] match
if ($i >= 0)
{
$i--;
$j--;
}
}
return $res;
}
// Driver program
$A = "EACBD";
$B = "EABCD";
echo "Minimum number of operations ".
"required is ". minOps($A, $B);
return 0;
?>
Output:
Minimum number of operations required is 3
Time Complexity: O(n), please note that i is always decremented (in while loop and in if), and the for loop starts from n-1 and runs while i >= 0.
Auxiliary Space: O(1).
Thanks to Gaurav Ahirwar for above solution.
Similar Reads
Minimum number of given operations required to convert a string to another string Given two strings S and T of equal length. Both strings contain only the characters '0' and '1'. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: Swap any two characters of the string.Replace a '0' with a '1' or vice
14 min read
Minimum number of given operations required to make two strings equal Given two strings A and B, both strings contain characters a and b and are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert first string into second string by doing the minimum number of the following operations: If _ is at position i then _ can be swapped w
15 min read
Minimum number of operations required to obtain a given Binary String Given a binary strings S of length N, the task is to obtain S from a string, say T, of length N consisting only of zeroes, by minimum number of operations. Each operation involves choosing any index i from string S and flipping all the bits at indices [i, N - 1] of the string T. Examples: Input: S =
8 min read
Minimum operations to transform given string to another by moving characters to front or end Given two Strings S and T of length N consisting of lowercase alphabets, which are permutations of each other, the task is to print the minimum number of operations to convert S to T. In one operation, pick any character of the string S and move it either to the start or end of the string S. Example
13 min read
Minimum cost to convert one given string to another using swap, insert or delete operations Given two strings A and B of length N and M respectively, the task is to find the minimum cost to convert string A to B using the following operations: A character of string A can be swapped from another character of the same string. Cost = 0.A character can be deleted from string B or can be insert
6 min read
Minimum move to end operations to make all strings equal Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end. Examples: Input: n = 2, arr[] = {"molzv", "lzvmo"}Output: 2Explanation: In first string, we remove first element("m") from first s
13 min read
Check if it is possible to transform one string to another Given two strings s1 and s2(all letters in uppercase). Check if it is possible to convert s1 to s2 by performing following operations. Make some lowercase letters uppercase. Delete all the lowercase letters. Examples: Input : s1 = daBcd s2 = ABC Output : yes Explanation : daBcd -> dABCd -> ABC
7 min read
Maximum weight transformation of a given string Given a string consisting of only A's and B's. We can transform the given string to another string by toggling any character. Thus many transformations of the given string are possible. The task is to find Weight of the maximum weight transformation. Weight of a string is calculated using below form
9 min read
Create lexicographically minimum String using given operation Given a string s of length N consisting of digits from 0 to 9. Find the lexicographically minimum sequence that can be obtained from given string s by performing the given operations: Selecting any position i in the string and delete the digit 'd' at ith position, Insert min(d+1, 9) on any position
7 min read
Minimum cost to convert str1 to str2 with the given operations Given two strings of equal lengths str1 and str2 consist of characters 'a' and 'b' only. The following operations can be performed on str1: Any character can be changed from 'a' to 'b' or from 'b' to 'a' with 1 unit cost.Any two characters str1[i] and str1[j] can be swapped with cost |i - j|. The ta
6 min read