Saturday, 23 Oct 2021

# Minimum subsequences of a string A required to be appended to obtain the string B

Minimum subsequences of a string A required to be appended to obtain the string B
Given two strings A and B, the task is to count the minimum number of operations required to construct the string B by following operations:
Select a subsequence of the string A.
Append the subsequence at the newly formed string (initially empty).
Print the minimum count of operations required. If it is impossible to make the new string equal to B by applying the given operations, then print -1.
Examples:

Input: A = “abc”, B = “abac”Output: 2Explanation:Initially, C = “”.Step 1: Select subsequence “ab” from string A and append it to the empty string C, i.e. C = “ab”.Step 2: Select subsequence “ac” from string A and append it to the end of string C, i.e. C = “abac”.Now, the string C is same as string B.Therefore, count of operations required is 2.
Input: A = “geeksforgeeks”, B = “programming”Output: -1

Approach: Follow the below steps to solve this problem:Initialize a Map to map characters present in the string A with their respective indices.
For each character in string A, keep track of all of its occurrences.
Initialize a variable, say ans, to store the count of operations required. As the number of operations must be greater than 1, set ans = 1.
Iterate over the characters of string B and check if the character is present in the string A or not by using the Map.
Lastly, maximize the length of the subsequence chosen from the string A for each operation.
Finally, print the minimum operations required.
Below is the implementation of the above approach:

C++

#include
using namespace std;

void countminOpsToConstructAString(string A,
string B)
{

int N = A.length();

int i = 0;

map mp;

for (i = 0; i < N; i++) {         mp[A[i]].insert(i);     }                       int previous = -1;             int ans = 1;             for (i = 0; i < B.length(); i++) {         char ch = B[i];                              if (mp[ch].size() == 0) {             cout