Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Minimum subsequences of a string A required to be appended to obtain the string B
Next article icon

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

Last Updated : 15 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 3 
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.
 

C++




// C++ implementation for minimum
// number of subsequences required
// to convert one string to another
 
#include <iostream>
using namespace std;
 
// Function to find the minimum number
// of subsequences required to convert
// one string to another
// S2 == A and S1 == B
int findMinimumSubsequences(string A,
                            string B){
     
    // At least 1 subsequence is required
    // Even in best case, when A is same as B
    int numberOfSubsequences = 1;
     
    // size of B
    int sizeOfB = B.size();
     
    // size of A
    int sizeOfA = A.size();
    int inf = 1000000;
 
    // Create an 2D array next[][]
    // of size 26 * sizeOfB to store
    // the next occurrence of a character
    // ('a' to 'z') as an index [0, sizeOfA - 1]
    int next[26][sizeOfB];
 
    // Array Initialization with infinite
    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < sizeOfB; j++) {
            next[i][j] = inf;
        }
    }
 
    // Loop to Store the values of index
    for (int i = 0; i < sizeOfB; i++) {
        next[B[i] - 'a'][i] = i;
    }
     
    // If the value of next[i][j]
    // is infinite then update it with
    // next[i][j + 1]
    for (int i = 0; i < 26; i++) {
        for (int j = sizeOfB - 2; j >= 0; j--) {
            if (next[i][j] == inf) {
                next[i][j] = next[i][j + 1];
            }
        }
    }
 
    // Greedy algorithm to obtain the maximum
    // possible subsequence of B to cover the
    // remaining string of A using next subsequence
    int pos = 0;
    int i = 0;
     
    // Loop to iterate over the string A
    while (i < sizeOfA) {
         
        // Condition to check if the character is
        // not present in the string B
        if (pos == 0 &&
           next[A[i] - 'a'][pos] == inf) {
            numberOfSubsequences = -1;
            break;
        }
         
        // Condition to check if there
        // is an element in B matching with
        // character A[i] on or next to B[pos]
        // given by next[A[i] - 'a'][pos]
        else if (pos < sizeOfB &&
                  next[A[i] - 'a'][pos] < inf) {
            int nextIndex = next[A[i] - 'a'][pos] + 1;
            pos = nextIndex;
            i++;
        }
         
        // Condition to check if reached at the end
        // of B or no such element exists on
        // or next to A[pos], thus increment number
        // by one and reinitialise pos to zero
        else {
            numberOfSubsequences++;
            pos = 0;
        }
    }
    return numberOfSubsequences;
}
 
// Driver Code
int main()
{
    string A = "aacbe";
    string B = "aceab";
  
cout << findMinimumSubsequences(A, B);
 
    return 0;
}
 
 

Java




// Java implementation for minimum
// number of subsequences required
// to convert one String to another
class GFG
{
 
// Function to find the minimum number
// of subsequences required to convert
// one String to another
// S2 == A and S1 == B
static int findMinimumSubsequences(String A,
                            String B)
{
     
    // At least 1 subsequence is required
    // Even in best case, when A is same as B
    int numberOfSubsequences = 1;
     
    // size of B
    int sizeOfB = B.length();
     
    // size of A
    int sizeOfA = A.length();
    int inf = 1000000;
 
    // Create an 2D array next[][]
    // of size 26 * sizeOfB to store
    // the next occurrence of a character
    // ('a' to 'z') as an index [0, sizeOfA - 1]
    int [][]next = new int[26][sizeOfB];
 
    // Array Initialization with infinite
    for (int i = 0; i < 26; i++) {
        for (int j = 0; j < sizeOfB; j++) {
            next[i][j] = inf;
        }
    }
 
    // Loop to Store the values of index
    for (int i = 0; i < sizeOfB; i++) {
        next[B.charAt(i) - 'a'][i] = i;
    }
     
    // If the value of next[i][j]
    // is infinite then update it with
    // next[i][j + 1]
    for (int i = 0; i < 26; i++) {
        for (int j = sizeOfB - 2; j >= 0; j--) {
            if (next[i][j] == inf) {
                next[i][j] = next[i][j + 1];
            }
        }
    }
 
    // Greedy algorithm to obtain the maximum
    // possible subsequence of B to cover the
    // remaining String of A using next subsequence
    int pos = 0;
    int i = 0;
     
    // Loop to iterate over the String A
    while (i < sizeOfA) {
         
        // Condition to check if the character is
        // not present in the String B
        if (pos == 0 &&
        next[A.charAt(i)- 'a'][pos] == inf) {
            numberOfSubsequences = -1;
            break;
        }
         
        // Condition to check if there
        // is an element in B matching with
        // character A[i] on or next to B[pos]
        // given by next[A[i] - 'a'][pos]
        else if (pos < sizeOfB &&
                next[A.charAt(i) - 'a'][pos] < inf) {
            int nextIndex = next[A.charAt(i) - 'a'][pos] + 1;
            pos = nextIndex;
            i++;
        }
         
        // Condition to check if reached at the end
        // of B or no such element exists on
        // or next to A[pos], thus increment number
        // by one and reinitialise pos to zero
        else {
            numberOfSubsequences++;
            pos = 0;
        }
    }
    return numberOfSubsequences;
}
 
// Driver Code
public static void main(String[] args)
{
    String A = "aacbe";
    String B = "aceab";
 
    System.out.print(findMinimumSubsequences(A, B));
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python3




# Python3 implementation for minimum
# number of subsequences required
# to convert one to another
 
# Function to find the minimum number
# of subsequences required to convert
# one to another
# S2 == A and S1 == B
def findMinimumSubsequences(A, B):
 
    # At least 1 subsequence is required
    # Even in best case, when A is same as B
    numberOfSubsequences = 1
 
    # size of B
    sizeOfB = len(B)
 
    # size of A
    sizeOfA = len(A)
    inf = 1000000
 
    # Create an 2D array next[][]
    # of size 26 * sizeOfB to store
    # the next occurrence of a character
    # ('a' to 'z') as an index [0, sizeOfA - 1]
    next = [[ inf for i in range(sizeOfB)] for i in range(26)]
 
    # Loop to Store the values of index
    for i in range(sizeOfB):
        next[ord(B[i]) - ord('a')][i] = i
 
    # If the value of next[i][j]
    # is infinite then update it with
    # next[i][j + 1]
    for i in range(26):
        for j in range(sizeOfB-2, -1, -1):
            if (next[i][j] == inf):
                next[i][j] = next[i][j + 1]
 
    # Greedy algorithm to obtain the maximum
    # possible subsequence of B to cover the
    # remaining of A using next subsequence
    pos = 0
    i = 0
 
    # Loop to iterate over the A
    while (i < sizeOfA):
 
        # Condition to check if the character is
        # not present in the B
        if (pos == 0 and
        next[ord(A[i]) - ord('a')][pos] == inf):
            numberOfSubsequences = -1
            break
 
        # Condition to check if there
        # is an element in B matching with
        # character A[i] on or next to B[pos]
        # given by next[A[i] - 'a'][pos]
        elif (pos < sizeOfB and
                next[ord(A[i]) - ord('a')][pos] < inf) :
            nextIndex = next[ord(A[i]) - ord('a')][pos] + 1
            pos = nextIndex
            i += 1
 
        # Condition to check if reached at the end
        # of B or no such element exists on
        # or next to A[pos], thus increment number
        # by one and reinitialise pos to zero
        else :
            numberOfSubsequences += 1
            pos = 0
 
    return numberOfSubsequences
 
# Driver Code
if __name__ == '__main__':
    A = "aacbe"
    B = "aceab"
    print(findMinimumSubsequences(A, B))
     
# This code is contributed by mohit kumar 29
 
 

C#




// C# implementation for minimum
// number of subsequences required
// to convert one String to another
using System;
 
class GFG
{
 
// Function to find the minimum number
// of subsequences required to convert
// one String to another
// S2 == A and S1 == B
static int findMinimumSubsequences(String A,
                                   String B)
{
     
    // At least 1 subsequence is required
    // Even in best case, when A is same as B
    int numberOfSubsequences = 1;
     
    // size of B
    int sizeOfB = B.Length;
     
    // size of A
    int sizeOfA = A.Length;
    int inf = 1000000;
 
    // Create an 2D array next[,]
    // of size 26 * sizeOfB to store
    // the next occurrence of a character
    // ('a' to 'z') as an index [0, sizeOfA - 1]
    int [,]next = new int[26,sizeOfB];
 
    // Array Initialization with infinite
    for (int i = 0; i < 26; i++)
    {
        for (int j = 0; j < sizeOfB; j++)
        {
            next[i, j] = inf;
        }
    }
 
    // Loop to Store the values of index
    for (int i = 0; i < sizeOfB; i++)
    {
        next[B[i] - 'a', i] = i;
    }
     
    // If the value of next[i,j]
    // is infinite then update it with
    // next[i,j + 1]
    for (int i = 0; i < 26; i++)
    {
        for (int j = sizeOfB - 2; j >= 0; j--)
        {
            if (next[i, j] == inf)
            {
                next[i, j] = next[i, j + 1];
            }
        }
    }
 
    // Greedy algorithm to obtain the maximum
    // possible subsequence of B to cover the
    // remaining String of A using next subsequence
    int pos = 0;
    int I = 0;
     
    // Loop to iterate over the String A
    while (I < sizeOfA)
    {
         
        // Condition to check if the character is
        // not present in the String B
        if (pos == 0 &&
            next[A[I]- 'a', pos] == inf)
        {
            numberOfSubsequences = -1;
            break;
        }
         
        // Condition to check if there
        // is an element in B matching with
        // character A[i] on or next to B[pos]
        // given by next[A[i] - 'a',pos]
        else if (pos < sizeOfB &&
                next[A[I] - 'a',pos] < inf)
        {
            int nextIndex = next[A[I] - 'a',pos] + 1;
            pos = nextIndex;
            I++;
        }
         
        // Condition to check if reached at the end
        // of B or no such element exists on
        // or next to A[pos], thus increment number
        // by one and reinitialise pos to zero
        else
        {
            numberOfSubsequences++;
            pos = 0;
        }
    }
    return numberOfSubsequences;
}
 
// Driver Code
public static void Main(String[] args)
{
    String A = "aacbe";
    String B = "aceab";
 
    Console.Write(findMinimumSubsequences(A, B));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// Javascript implementation for minimum
// number of subsequences required
// to convert one String to another
 
// Function to find the minimum number
// of subsequences required to convert
// one String to another
// S2 == A and S1 == B
function findMinimumSubsequences(A,B)
{
    // At least 1 subsequence is required
    // Even in best case, when A is same as B
    let numberOfSubsequences = 1;
       
    // size of B
    let sizeOfB = B.length;
       
    // size of A
    let sizeOfA = A.length;
    let inf = 1000000;
   
    // Create an 2D array next[][]
    // of size 26 * sizeOfB to store
    // the next occurrence of a character
    // ('a' to 'z') as an index [0, sizeOfA - 1]
    let next = new Array(26);
   
    // Array Initialization with infinite
    for (let i = 0; i < 26; i++) {
        next[i]=new Array(sizeOfB);
        for (let j = 0; j < sizeOfB; j++) {
            next[i][j] = inf;
        }
    }
   
    // Loop to Store the values of index
    for (let i = 0; i < sizeOfB; i++) {
        next[B[i].charCodeAt(0) - 'a'.charCodeAt(0)][i] = i;
    }
       
    // If the value of next[i][j]
    // is infinite then update it with
    // next[i][j + 1]
    for (let i = 0; i < 26; i++) {
        for (let j = sizeOfB - 2; j >= 0; j--) {
            if (next[i][j] == inf) {
                next[i][j] = next[i][j + 1];
            }
        }
    }
   
    // Greedy algorithm to obtain the maximum
    // possible subsequence of B to cover the
    // remaining String of A using next subsequence
    let pos = 0;
    let i = 0;
       
    // Loop to iterate over the String A
    while (i < sizeOfA) {
           
        // Condition to check if the character is
        // not present in the String B
        if (pos == 0 &&
        next[A[i].charCodeAt(0)- 'a'.charCodeAt(0)][pos] == inf) {
            numberOfSubsequences = -1;
            break;
        }
           
        // Condition to check if there
        // is an element in B matching with
        // character A[i] on or next to B[pos]
        // given by next[A[i] - 'a'][pos]
        else if (pos < sizeOfB &&
                next[A[i].charCodeAt(0) - 'a'.charCodeAt(0)][pos] < inf) {
            let nextIndex = next[A[i].charCodeAt(0) - 'a'.charCodeAt(0)][pos] + 1;
            pos = nextIndex;
            i++;
        }
           
        // Condition to check if reached at the end
        // of B or no such element exists on
        // or next to A[pos], thus increment number
        // by one and reinitialise pos to zero
        else {
            numberOfSubsequences++;
            pos = 0;
        }
    }
    return numberOfSubsequences;
}
 
// Driver Code
let A = "aacbe";
let B = "aceab";
document.write(findMinimumSubsequences(A, B));
 
 
// This code is contributed by unknown2108
</script>
 
 
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)
 



Next Article
Minimum subsequences of a string A required to be appended to obtain the string B
author
dt_kanha
Improve
Article Tags :
  • Algorithms
  • DSA
  • Greedy
  • Strings
  • Technical Scripter
  • subsequence
  • Technical Scripter 2019
Practice Tags :
  • Algorithms
  • Greedy
  • Strings

Similar Reads

  • Minimum number of subsequences required to convert one string to another
    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"
    8 min read
  • Minimum number of given operations required to convert a string to another string
    Given two strings S and T of equal length. Both strings contain only the characters '0' and '1'. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: Swap any two characters of the string.Replace a '0' with a '1' or vice
    15 min read
  • Replace even-indexed characters of minimum number of substrings to convert a string to another
    Given two strings, str1 and str2 of length N, the task is to convert the string str1 to string str2 by selecting a substring and replacing all characters present at even indices of the substring by any possible characters, even number of times. Examples: Input: str1 = "abcdef", str2 = "ffffff" Outpu
    7 min read
  • Transform One String to Another using Minimum Number of Given Operation
    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",
    15+ min read
  • 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
    8 min read
  • Minimum removal of subsequences of distinct consecutive characters required to empty a given string
    Given a binary string, str, the task is to empty the given string by minimum number of removals of a single character or a subsequence containing distinct consecutive characters from str. Examples: Input: str = "0100100111" Output: 3 Explanation: Removing the subsequence "010101" from the string mod
    6 min read
  • Minimum number of given operations required to make two strings equal
    Given two strings A and B, both strings contain characters a and b and are of equal lengths. There is one _ (empty space) in both the strings. The task is to convert first string into second string by doing the minimum number of the following operations: If _ is at position i then _ can be swapped w
    15 min read
  • Maximum length prefix of one string that occurs as subsequence in another
    Given two strings s and t. The task is to find maximum length of some prefix of the string S which occur in string t as subsequence. Examples : Input : s = "digger" t = "biggerdiagram" Output : 3 digger biggerdiagram Prefix "dig" of s is longest subsequence in t. Input : s = "geeksforgeeks" t = "agb
    5 min read
  • Maximum number of times a given string needs to be concatenated to form a substring of another string
    Given two strings S1 and S2 of length N and M respectively, the task is to find the maximum value of times the string S2 needs to be concatenated, such that it is a substring of the string S1. Examples: Input: S1 = "ababc", S2 = "ab"Output: 2Explanation: After concatenating S2 exactly twice, the str
    12 min read
  • Minimize count of alternating subsequences to divide given Binary String with subsequence number
    Given a binary string S of length N. The task is to find the following: The minimum number of subsequences, string S can be divided into, such that the subsequence does not contain adjacent zeroes or ones.Subsequence number to which each character of string S belongs. If there are many answers, outp
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences