VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-number-of-subsequences-required-to-convert-one-string-to-another-using-greedy-algorithm/

⇱ Minimum number of subsequences required to convert one string to another using Greedy Algorithm - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum number of subsequences required to convert one string to another using Greedy Algorithm

Last Updated : 12 Jul, 2025

Given two strings A and B consists of lowercase letters, the task to find the minimum number of subsequence required to form A from B. If it is impossible to form, print -1.
Examples: 
 

Input: A = "aacbe", B = "aceab" 
Output:
Explanation: 
The minimum number of subsequences required for creating A from B is "aa", "cb" and "e".
Input: A = "geeks", B = "geekofthemonth" 
Output: -1 
Explanation: 
It is not possible to create A, as the character 's' is missing in B. 
 


 


For brute-force approach refer here 
Minimum number of subsequences required to convert one string to another
Greedy Approach: 
 

  1. Create a 2D-Array of 26 * size_of_string_B to store the occurrence of indices of the character and initialize the array with 'infinite' values.
  2. Maintain the 2D Array with indices of the character in the String B
  3. If the value of any element of the 2D Array is infinite, then update the value with the next value in the same row.
  4. Initialize the position of the pointer to 0
  5. Iterate the String A and for each character - 
    • If the position of the pointer is 0 and if that position in the 2D Array is infinite, then the character is not present in the string B.
    • If the value in the 2D Array is not equal to infinite, then update the value of the position with the value present at the 2D Array for that position of the pointer, Because the characters before it cannot be considered in the subsequence.


Below is the implementation of the above approach.
 


Output: 
3

 

Time Complexity: O(N), where N is the length of string to be formed (here A) 
Auxiliary Space Complexity: O(N), where N is the length of string to be formed (here A)
 

Comment
Article Tags: