Minimum operations to convert String A to String B
Last Updated :
26 Apr, 2023
Given two strings consisting of lowercase alphabets A and B, both of the same length. Each character of both the strings is either a lowercase letter or a question mark '?'. The task is to find the minimum number of operations required to convert A to B, in one operation you can choose an index i, if A[i] is a vowel convert it to a consonant, and if A[i] is a consonant convert it to vowel. Prior to performing any operation you need to replace each occurrence of '?' in both strings A and B with the same lowercase letter.
Note: For conversion from a consonant to a consonant, we need two steps: consonant->vowel->consonant. The same shall be true for vowel-to-vowel conversion.
Examples:
Input: A: "abcd?", B: "acxe?"
Output: 1
Explanation: We can replace the ? character by any alphabet and the number of operations will be same.
Input: A = "ab?c?", B = "aeg?k"
Output: 4
Explanation: If each instance of ? is replaced by 'u' . Then A = "ab?c?", B = "aeg?k". The number of operations required is 4 which the least one can get.
Approach: To solve the problem follow the below idea:
The number of characters in the lowercase English alphabet is 26. This suggests that we can first replace each instance of '?' in both the strings with each alphabet (a - z) at one time. Now we have two newly complete strings without any occurrence of '?' we can calculate the number of operations it would take to convert A to B. Each character when placed in the location of '?' for both the strings gives some number of operations. The minimum number of these operations gives the final answer.
Illustration:
It is clear from the problem statement itself that once we replace the '?' in both the strings with the appropriate lowercase alphabet, then we only need to calculate the number of steps to convert from A to B.
Say A : "a?pc?", B : "qfc?d"
Upon trying brute-force, one can observe that for the above testcase one can conclude that replacing the '?' by 'a' takes only 6 operations.
Number of operations for each index:
- For i = 1, a -> q : 1
- i = 2, a -> f : 1
- i = 3, p -> c : 2
- i = 4, c -> a : 1
- i = 5, a -> d : 1
Hence, the total number of operations becomes 6.
The above approach simply replaces the question mark with each of the lowercase alphabet and checks for which alphabet the number of operations is minimum.
Steps to follow to implement the above approach:
- Initialize two auxiliary strings P and Q.
- Iterate for each alphabet from a - z and replace each instance of '?' in both strings with that alphabet.
- Store the newly formed strings into P and Q.
- Compute the number of operations required to convert P to Q and store it in some cnt variable.
- Update the min_op if the current value of cnt is less than min_op.
- Repeat 3-5 for the next alphabet until z.
Below is the code to implement the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Checking if certain character is
// vowel or consonant
int isVowel(char c)
{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u')
return true;
else
return false;
}
// Function to compute minimum number
// of required operations
int solve(string A, string B)
{
// If both strings are already
// equal no. of operation required
if (A == B) {
return 0;
}
int n = A.size(), minOp = INT_MAX, cnt = 0;
// Two auxiliary strings
string P = "", Q = "";
// Iterate for both the strings
// replacing the each occurrence of
// '?' with each alphabet (a-z) and
// then compute the number
// of operations
for (int j = 0; j < 26; j++) {
// Re-initialize both P and Q and
// operation counter i.e. cnt
P = A, Q = B;
cnt = 0;
// Replace all the occurrences of
// '?' in both strings with each
// English alphabet iteratively.
for (int i = 0; i < n; i++) {
if (P[i] == '?')
P[i] = char('a' + j);
if (Q[i] == '?')
Q[i] = char('a' + j);
}
// Calculate the number
// of operations required
for (int i = 0; i < n; i++) {
// if both characters are
// same then no operation
// is required
if (P[i] == Q[i]) {
continue;
}
// if both characters are
// either vowels or consonants
// we need 2 operations as
// vowel -> consonant -> vowel
else if ((isVowel(P[i]) && isVowel(Q[i]))
|| (!isVowel(P[i])
&& !isVowel(Q[i]))) {
cnt += 2;
}
// if one character is vowel
// and other is consonant
// then only one conversion
// is required
else {
cnt += 1;
}
}
// Update the variable minOp if
// number of operations for
// current alphabet is lesser
// than existing value
minOp = min(minOp, cnt);
}
// Return final answer
return minOp;
}
// Driver Code
int main()
{
// TestCase 1
string A = "ab?c?", B = "aeg?k";
cout << solve(A, B) << endl;
// TestCase 2
A = "am??x", B = "xd?fc";
cout << solve(A, B) << endl;
// TestCase 3
A = "a?pc?", B = "qfc?d";
cout << solve(A, B) << endl;
return 0;
}
Python3
def isVowel(c):
if c == 'a' or c == 'e' or c == 'i' or c == 'o' or c == 'u':
return True
else:
return False
def solve(A, B):
if A == B:
return 0
n = len(A)
minOp = float('inf')
for j in range(26):
P, Q = A, B
cnt = 0
for i in range(n):
if P[i] == '?':
P = P[:i] + chr(ord('a') + j) + P[i+1:]
if Q[i] == '?':
Q = Q[:i] + chr(ord('a') + j) + Q[i+1:]
for i in range(n):
if P[i] == Q[i]:
continue
elif ((isVowel(P[i]) and isVowel(Q[i])) or (not isVowel(P[i]) and not isVowel(Q[i]))):
cnt += 2
else:
cnt += 1
minOp = min(minOp, cnt)
return minOp
# Driver Code
if __name__ == '__main__':
# TestCase 1
A = "ab?c?"
B = "aeg?k"
print(solve(A, B))
# TestCase 2
A = "am??x"
B = "xd?fc"
print(solve(A, B))
# TestCase 3
A = "a?pc?"
B = "qfc?d"
print(solve(A, B))
C#
// C# code for the above approach:
using System;
public class Solution {
// Checking if certain character is vowel or consonant
public static bool isVowel(char c)
{
if (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u') {
return true;
}
else {
return false;
}
}
// Function to compute minimum number of required
// operations
public static int solve(string A, string B)
{
// If both strings are already equal no. of
// operation required
if (A == B) {
return 0;
}
int n = A.Length, minOp = int.MaxValue, cnt = 0;
// Two auxiliary strings
string P = "", Q = "";
// Iterate for both the strings replacing the each
// occurrence of '?' with each alphabet (a-z) and
// then compute the number of operations
for (int j = 0; j < 26; j++) {
// Re-initialize both P and Q and operation
// counter i.e. cnt
P = A;
Q = B;
cnt = 0;
// Replace all the occurrences of '?' in both
// strings with each English alphabet
// iteratively.
for (int i = 0; i < n; i++) {
if (P[i] == '?') {
P = P.Remove(i, 1).Insert(
i, char.ConvertFromUtf32('a' + j));
}
if (Q[i] == '?') {
Q = Q.Remove(i, 1).Insert(
i, char.ConvertFromUtf32('a' + j));
}
}
// Calculate the number of operations required
for (int i = 0; i < n; i++) {
// if both characters are same then no
// operation is required
if (P[i] == Q[i]) {
continue;
}
// if both characters are either vowels or
// consonants we need 2 operations as vowel
// -> consonant -> vowel
else if ((isVowel(P[i]) && isVowel(Q[i]))
|| (!isVowel(P[i])
&& !isVowel(Q[i]))) {
cnt += 2;
}
// if one character is vowel and other is
// consonant then only one conversion is
// required
else {
cnt += 1;
}
}
// Update the variable minOp if number of
// operations for current alphabet is lesser
// than existing value
minOp = Math.Min(minOp, cnt);
}
// Return final answer
return minOp;
}
// Main function
public static void Main()
{
// TestCase 1
string A = "ab?c?", B = "aeg?k";
Console.WriteLine(solve(A, B));
// TestCase 2
A = "am??x";
B = "xd?fc";
Console.WriteLine(solve(A, B));
// TestCase 3
A = "a?pc?";
B = "qfc?d";
Console.WriteLine(solve(A, B));
}
}
JavaScript
// Function to check if a given character is vowel or consonant
function isVowel(c) {
if (c === 'a' || c === 'e' || c === 'i' || c === 'o' || c === 'u') {
return true;
} else {
return false;
}
}
// Function to compute minimum number of required operations to convert string A to string B
function solve(A, B) {
// If both strings are already equal, no operation is required
if (A === B) {
return 0;
}
// Initialize variables
let n = A.length;
let minOp = Infinity;
let cnt = 0;
let P = '';
let Q = '';
// Iterate for each English alphabet from a to z
for (let j = 0; j < 26; j++) {
// Re-initialize P, Q and cnt for each alphabet
P = A;
Q = B;
cnt = 0;
// Replace all the occurrences of '?' in both strings with each English alphabet iteratively
for (let i = 0; i < n; i++) {
if (P[i] === '?') {
P = P.substr(0, i) + String.fromCharCode('a'.charCodeAt(0) + j) + P.substr(i + 1);
}
if (Q[i] === '?') {
Q = Q.substr(0, i) + String.fromCharCode('a'.charCodeAt(0) + j) + Q.substr(i + 1);
}
}
// Compute the number of operations required to convert P to Q
for (let i = 0; i < n; i++) {
if (P[i] === Q[i]) {
// If both characters are same then no operation is required
continue;
} else if ((isVowel(P[i]) && isVowel(Q[i])) || (!isVowel(P[i]) && !isVowel(Q[i]))) {
// If both characters are either vowels or consonants, we need 2 operations as vowel -> consonant -> vowel
cnt += 2;
} else {
// If one character is vowel and other is consonant, then only one conversion is required
cnt += 1;
}
}
// Update the variable minOp if number of operations for current alphabet is lesser than existing value
minOp = Math.min(minOp, cnt);
}
// Return final answer
return minOp;
}
// Test Cases
let A = 'ab?c?', B = 'aeg?k';
console.log(solve(A, B));
A = 'am??x', B = 'xd?fc';
console.log(solve(A, B));
A = 'a?pc?', B = 'qfc?d';
console.log(solve(A, B));
Java
import java.util.*;
public class Main {
// Checking if certain character is
// vowel or consonant
public static boolean isVowel(char c) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o'
|| c == 'u') {
return true;
} else {
return false;
}
}
// Function to compute minimum number
// of required operations
public static int solve(String A, String B) {
// If both strings are already
// equal no. of operation required
if (A.equals(B)) {
return 0;
}
int n = A.length(), minOp = Integer.MAX_VALUE, cnt = 0;
// Two auxiliary strings
String P = "", Q = "";
// Iterate for both the strings
// replacing the each occurrence of
// '?' with each alphabet (a-z) and
// then compute the number
// of operations
for (int j = 0; j < 26; j++) {
// Re-initialize both P and Q and
// operation counter i.e. cnt
P = A; Q = B;
cnt = 0;
// Replace all the occurrences of
// '?' in both strings with each
// English alphabet iteratively.
for (int i = 0; i < n; i++) {
if (P.charAt(i) == '?') {
P = P.substring(0, i) + (char)('a' + j) + P.substring(i+1);
}
if (Q.charAt(i) == '?') {
Q = Q.substring(0, i) + (char)('a' + j) + Q.substring(i+1);
}
}
// Calculate the number
// of operations required
for (int i = 0; i < n; i++) {
// if both characters are
// same then no operation
// is required
if (P.charAt(i) == Q.charAt(i)) {
continue;
}
// if both characters are
// either vowels or consonants
// we need 2 operations as
// vowel -> consonant -> vowel
else if ((isVowel(P.charAt(i)) && isVowel(Q.charAt(i)))
|| (!isVowel(P.charAt(i))
&& !isVowel(Q.charAt(i)))) {
cnt += 2;
}
// if one character is vowel
// and other is consonant
// then only one conversion
// is required
else {
cnt += 1;
}
}
// Update the variable minOp if
// number of operations for
// current alphabet is lesser
// than existing value
minOp = Math.min(minOp, cnt);
}
// Return final answer
return minOp;
}
// Driver Code
public static void main(String[] args) {
// TestCase 1
String A = "ab?c?", B = "aeg?k";
System.out.println(solve(A, B));
// TestCase 2
A = "am??x"; B = "xd?fc";
System.out.println(solve(A, B));
// TestCase 3
A = "a?pc?"; B = "qfc?d";
System.out.println(solve(A, B));
}
}
Time Complexity: O(N*26) ~ O(N)
Auxiliary Space: O(N), auxiliary strings of size N are being used.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem