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;
}
unordered_map< char , int > m;
int n = A.length();
for ( int i = 0; i < n; i++) {
if (m.count(A[i]))
m[A[i]]++;
else
m[A[i]] = 1;
}
for ( int i = 0; i < n; i++) {
if (m.count(B[i]))
m[B[i]]--;
}
for ( auto it : m) {
if (it.second != 0)
return -1;
}
int i = n - 1, j = n - 1;
int res = 0;
while (i >= 0 && j >= 0) {
while (i >= 0 && A[i] != B[j]) {
res++;
i--;
}
i--;
j--;
}
return res;
}
int main()
{
string A = "EACBD" ;
string B = "EABCD" ;
cout << "Minimum number of operations required is " << transform(A, B) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static int transform(String A, String B)
{
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));
}
}
|
Python3
def transform(A, B):
if len (A) ! = len (B):
return - 1
m = {}
n = len (A)
for i in range (n):
if A[i] in m:
m[A[i]] + = 1
else :
m[A[i]] = 1
for i in range (n):
if B[i] in m:
m[B[i]] - = 1
for key in m:
if m[key] ! = 0 :
return - 1
i, j = n - 1 , n - 1
res = 0
while i > = 0 and j > = 0 :
while i > = 0 and A[i] ! = B[j]:
res + = 1
i - = 1
i - = 1
j - = 1
return res
A = "EACBD"
B = "EABCD"
print ( "Minimum number of operations required is" , transform(A, B))
|
Javascript
function transform(A, B) {
if (A.length !== B.length) {
return -1;
}
const m = {};
const n = A.length;
for (let i = 0; i < n; i++) {
if (m[A[i]]) {
m[A[i]]++;
} else {
m[A[i]] = 1;
}
}
for (let i = 0; i < n; i++) {
if (m[B[i]]) {
m[B[i]]--;
}
}
for (const char in m) {
if (m[char] !== 0) {
return -1;
}
}
let i = n - 1, j = n - 1;
let res = 0;
while (i >= 0 && j >= 0) {
while (i >= 0 && A[i] !== B[j]) {
res++;
i--;
}
i--;
j--;
}
return res;
}
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(N), since we are using a HashMap.
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++
#include <bits/stdc++.h>
using namespace std;
int minOps(string& A, string& B)
{
int m = A.length(), n = B.length();
if (n != m)
return -1;
int count[256];
memset (count, 0, sizeof (count));
for ( int i = 0; i < n; i++)
count[A[i]]++;
for ( int i = 0; i < n; i++)
count[B[i]]--;
for ( int i = 0; i < 256; i++)
if (count[i])
return -1;
int res = 0;
for ( int i = n - 1, j = n - 1; i >= 0;) {
while (i >= 0 && A[i] != B[j]) {
i--;
res++;
}
if (i >= 0) {
i--;
j--;
}
}
return res;
}
int main()
{
string A = "EACBD" ;
string B = "EABCD" ;
cout << "Minimum number of operations required is " << minOps(A, B);
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int minOps( char A[], char B[])
{
int m = strlen (A), n = strlen (B);
if (n != m)
return -1;
int count[256];
for ( int i = 0; i < 256; i++)
count[i] = 0;
for ( int i = 0; i < n; i++)
count[A[i]]++;
for ( int i = 0; i < n; i++)
count[B[i]]--;
for ( int i = 0; i < 256; i++)
if (count[i])
return -1;
int res = 0;
for ( int i = n - 1, j = n - 1; i >= 0;) {
while (i >= 0 && A[i] != B[j]) {
i--;
res++;
}
if (i >= 0) {
i--;
j--;
}
}
return res;
}
int main()
{
char A[] = "EACBD" ;
char B[] = "EABCD" ;
printf ( "Minimum number of operations required is %d" , minOps(A, B));
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
public static int minOps(String A, String B)
{
if (A.length() != B.length())
return - 1 ;
int i, j, res = 0 ;
int count[] = new int [ 256 ];
for (i = 0 ; i < A.length(); i++) {
count[A.charAt(i)]++;
count[B.charAt(i)]--;
}
for (i = 0 ; i < 256 ; i++)
if (count[i] != 0 )
return - 1 ;
i = A.length() - 1 ;
j = B.length() - 1 ;
while (i >= 0 ) {
if (A.charAt(i) != B.charAt(j))
res++;
else
j--;
i--;
}
return res;
}
public static void main(String[] args)
{
String A = "EACBD" ;
String B = "EABCD" ;
System.out.println(
"Minimum number of operations required is "
+ minOps(A, B));
}
}
|
Python3
def minOps(A, B):
m = len (A)
n = len (B)
if n ! = m:
return - 1
count = [ 0 ] * 256
for i in range (n):
count[ ord (B[i])] + = 1
for i in range (n):
count[ ord (A[i])] - = 1
for i in range ( 256 ):
if count[i]:
return - 1
res = 0
i = n - 1
j = n - 1
while i > = 0 :
while i> = 0 and A[i] ! = B[j]:
i - = 1
res + = 1
if i > = 0 :
i - = 1
j - = 1
return res
A = "EACBD"
B = "EABCD"
print ( "Minimum number of operations required is " + str (minOps(A,B)))
|
C#
using System;
class GFG
{
public static int minOps( string A, string B)
{
if (A.Length != B.Length)
{
return -1;
}
int i, j, res = 0;
int [] count = new int [256];
for (i = 0; i < A.Length; i++)
{
count[A[i]]++;
count[B[i]]--;
}
for (i = 0; i < 256; i++)
{
if (count[i] != 0)
{
return -1;
}
}
i = A.Length - 1;
j = B.Length - 1;
while (i >= 0)
{
if (A[i] != B[j])
{
res++;
}
else
{
j--;
}
i--;
}
return res;
}
public static void Main( string [] args)
{
string A = "EACBD" ;
string B = "EABCD" ;
Console.WriteLine( "Minimum number of " +
"operations required is " +
minOps(A, B));
}
}
|
Javascript
<script>
function minOps(A, B)
{
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;
}
for (i = 0; i < A.length; i++)
{
count[A[i].charCodeAt(0)]++;
count[B[i].charCodeAt(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 (A[i] != B[j])
res++;
else
j--;
i--;
}
return res;
}
let A = "EACBD" ;
let B = "EABCD" ;
document.write( "Minimum number of " +
"operations required is " +
minOps(A, B));
</script>
|
PHP
<?php
function minOps( $A , $B )
{
$m = strlen ( $A );
$n = strlen ( $B );
if ( $n != $m )
return -1;
$count = array_fill (0,256,NULL);
for ( $i =0; $i < $n ; $i ++)
$count [ord( $B [ $i ])]++;
for ( $i =0; $i < $n ; $i ++)
$count [ord( $A [ $i ])]--;
for ( $i =0; $i <256; $i ++)
if ( $count [ $i ])
return -1;
$res = 0;
for ( $i = $n -1, $j = $n -1; $i >=0; )
{
while ( $i >=0 && $A [ $i ] != $B [ $j ])
{
$i --;
$res ++;
}
if ( $i >= 0)
{
$i --;
$j --;
}
}
return $res ;
}
$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.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above