Minimum number of subsequences required to convert one string to another Last Updated : 24 Feb, 2023 Comments Improve Suggest changes Like Article Like Report Given two strings A and B consisting of only lowercase letters, the task is to find the minimum number of subsequences required from A to form B. Examples: Input: A = "abbace" B = "acebbaae" Output: 3 Explanation: Sub-sequences "ace", "bba", "ae" from string A used to form string B Input: A = "abc" B = "cbacbacba" Output: 7 Approach: Maintain an array for each character of A which will store its indexes in increasing order.Traverse through each element of B and increase the counter whenever there is a need for new subsequence.Maintain a variable minIndex which will show that elements greater than this index can be taken in current subsequence otherwise increase the counter and update the minIndex to -1. Below is the implementation of the above approach. C++ // C++ program to find the Minimum number // of subsequences required to convert // one string to another #include <bits/stdc++.h> using namespace std; // Function to find the no of subsequences int minSubsequnces(string A, string B) { vector<int> v[26]; int minIndex = -1, cnt = 1, j = 0; int flag = 0; for (int i = 0; i < A.length(); i++) { // Push the values of indexes of each character int p = (int)A[i] - 97; v[p].push_back(i); } while (j < B.length()) { int p = (int)B[j] - 97; // Find the next index available in the array int k = upper_bound(v[p].begin(), v[p].end(), minIndex) - v[p].begin(); // If Character is not in string A if (v[p].size() == 0) { flag = 1; break; } // Check if the next index is not equal to the // size of array which means there is no index // greater than minIndex in the array if (k != v[p].size()) { // Update value of minIndex with this index minIndex = v[p][k]; j = j + 1; } else { // Update the value of counter // and minIndex for next operation cnt = cnt + 1; minIndex = -1; } } if (flag == 1) { return -1; } return cnt; } // Driver Code int main() { string A1 = "abbace"; string B1 = "acebbaae"; cout << minSubsequnces(A1, B1) << endl; return 0; } Java // Java program to find the Minimum number // of subsequences required to convert // one to another import java.util.*; class GFG { // This function finds the upper bound of a value // in an array static int upper_bound(int[] arr, int value) { int left = 0; int right = arr.length; // Using the binary search method while (left < right) { int mid = (left + right) / 2; if (arr[mid] <= value) { left = mid + 1; } else { right = mid; } } return left; } // Function to find the no of subsequences static int minSubsequnces(String A, String B) { int[][] v = new int[26][]; for (int i = 0; i < v.length; i++) { v[i] = new int[0]; } int minIndex = -1; int cnt = 1; int j = 0; int flag = 0; for (int i = 0; i < A.length(); i++) { // Push the values of indexes of each character int p = (int)A.charAt(i) - 97; v[p] = Arrays.copyOf(v[p], v[p].length + 1); v[p][v[p].length - 1] = i; } while (j < B.length()) { int p = (int)B.charAt(j) - 97; // Find the next index available in the array int k = upper_bound(v[p], minIndex); // If Character is not in A if (v[p].length == 0) { flag = 1; break; } // Check if the next index is not equal to the // size of array which means there is no index // greater than minIndex in the array if (k != v[p].length) { // Update value of minIndex with this index minIndex = v[p][k]; j = j + 1; } else { // Update the value of counter // and minIndex for next operation cnt = cnt + 1; minIndex = -1; } } if (flag == 1) { return -1; } return cnt; } // Driver Code public static void main(String[] args) { String A1 = "abbace"; String B1 = "acebbaae"; System.out.println(minSubsequnces(A1, B1)); } } // This code is contributed by phasing17 Python3 # Python3 program to find the Minimum number # of subsequences required to convert # one to another from bisect import bisect as upper_bound # Function to find the no of subsequences def minSubsequnces(A, B): v = [[] for i in range(26)] minIndex = -1 cnt = 1 j = 0 flag = 0 for i in range(len(A)): # Push the values of indexes of each character p = ord(A[i]) - 97 v[p].append(i) while (j < len(B)): p = ord(B[j]) - 97 # Find the next index available in the array k = upper_bound(v[p], minIndex) # If Character is not in A if (len(v[p]) == 0): flag = 1 break # Check if the next index is not equal to the # size of array which means there is no index # greater than minIndex in the array if (k != len(v[p])): # Update value of minIndex with this index minIndex = v[p][k] j = j + 1 else: # Update the value of counter # and minIndex for next operation cnt = cnt + 1 minIndex = -1 if (flag == 1): return -1 return cnt # Driver Code A1 = "abbace" B1 = "acebbaae" print(minSubsequnces(A1, B1)) # This code is contributed by mohit kumar 29 C# // C# program to find the Minimum number // of subsequences required to convert // one to another using System; class GFG { // This function finds the upper bound of a value // in an array static int upper_bound(int[] arr, int value) { int left = 0; int right = arr.Length; // Using the binary search method while (left < right) { int mid = (left + right) / 2; if (arr[mid] <= value) { left = mid + 1; } else { right = mid; } } return left; } // Function to find the no of subsequences static int minSubsequnces(string A, string B) { int[][] v = new int[26][]; for (int i = 0; i < v.Length; i++) { v[i] = new int[0]; } int minIndex = -1; int cnt = 1; int j = 0; int flag = 0; for (int i = 0; i < A.Length; i++) { // Push the values of indexes of each character int p = (int)A[i] - 97; Array.Resize(ref v[p], v[p].Length + 1); v[p][v[p].Length - 1] = i; } while (j < B.Length) { int p = (int)B[j] - 97; // Find the next index available in the array int k = upper_bound(v[p], minIndex); // If Character is not in A if (v[p].Length == 0) { flag = 1; break; } // Check if the next index is not equal to the // size of array which means there is no index // greater than minIndex in the array if (k != v[p].Length) { // Update value of minIndex with this index minIndex = v[p][k]; j = j + 1; } else { // Update the value of counter // and minIndex for next operation cnt = cnt + 1; minIndex = -1; } } if (flag == 1) { return -1; } return cnt; } // Driver Code static void Main(string[] args) { string A1 = "abbace"; string B1 = "acebbaae"; Console.WriteLine(minSubsequnces(A1, B1)); } } // This code is contributed by phasing17 JavaScript // Javascript program to find the Minimum number // of subsequences required to convert // one to another // This function finds the upper bound of a value // in an array function upper_bound(arr, value) { let left = 0; let right = arr.length; // Using the binary search method while (left < right) { const mid = Math.floor((left + right) / 2); if (arr[mid] <= value) { left = mid + 1; } else { right = mid; } } return left; } // Function to find the no of subsequences function minSubsequnces(A, B) { let v = Array.from({length: 26}, () => []); let minIndex = -1; let cnt = 1; let j = 0; let flag = 0; for (let i = 0; i < A.length; i++) { // Push the values of indexes of each character let p = A.charCodeAt(i) - 97; v[p].push(i); } while (j < B.length) { let p = B.charCodeAt(j) - 97; // Find the next index available in the array let k = upper_bound(v[p], minIndex); // If Character is not in A if (v[p].length == 0) { flag = 1; break; } // Check if the next index is not equal to the // size of array which means there is no index // greater than minIndex in the array if (k != v[p].length) { // Update value of minIndex with this index minIndex = v[p][k]; j = j + 1; } else { // Update the value of counter // and minIndex for next operation cnt = cnt + 1; minIndex = -1; } } if (flag == 1) { return -1; } return cnt; } // Driver Code let A1 = "abbace"; let B1 = "acebbaae"; console.log(minSubsequnces(A1, B1)); // This code is contributed by phasing17 Output: 3 Time Complexity: O(N1+N2) // N1 is the length of string A and N2 is the length of string B Auxiliary Space: O(26) Comment More infoAdvertise with us Next Article Minimum number of subsequences required to convert one string to another A AmanGupta65 Follow Improve Article Tags : Strings Greedy DSA subsequence Practice Tags : GreedyStrings Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example 12 min read Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an 8 min read Like