Transform string str1 into str2 by taking characters from string str3

Given three strings str1, str2 & str3. The task is to find whether string str1 can be transformed to string str2 by taking characters from str3. If yes then print “YES“, Else print “NO“.

Examples:

Input: str1 = “abyzf”, str2 = “abgdeyzf”, str3 = “poqgode”.
Output: YES
Explanation:
Remove ‘g’ from str3 and insert it after ‘b’ in str1, A = “abgyzf”, C=”poqode”
Remove ‘d’ from str3 and insert it after ‘g’ in str1, A = “abgdyzf”, C=”poqoe”
Remove ‘e’ from str3 and insert it after ‘d’ in str1, A = “abgdeyzf”, C=”poqo”
Therefore str1 is transform into str2.

Input: A = “abyzf”, B = “abcdeyzf”, C = “popode”.
Output: NO
Explanation:
It is not possible to transform A equal to C.

Approach: This problem can be solved using Greedy Approach.



  1. Compute the frequency of each charactors of string str3.
  2. Traverse the string str1 & str2 using two pointers(say i for str1 and j for str2) simultaneously and do the following:
    • If the characters at the ith index of str1 and jth index of str2 is same then, check for the next charactors.
    • If the characters at the ith index and jth index are not same, then check for the frequency of the str2[j] characters, if frequency is greater than 0 then increment the jth pointer and check for next pair of characters.
    • Else we can’t transform string str1 into string str2.
  3. After all the above iteration if both the pointers reaches end of the string respectively, then str1 can be transformed into str2.
  4. Else str1 cannot be transformed into str2.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to check whether str1 can
// be transformed to str2
void convertString(string str1, string str2,
                   string str3)
{
    // To store the frequency of
    // characters of string str3
    map<char, int> freq;
    for (int i = 0; str3[i]; i++) {
        freq[str3[i]]++;
    }
  
    // Declare two pointers & flag
    int ptr1 = 0;
    int ptr2 = 0;
    bool flag = true;
  
    // Traverse both the string and
    // check whether it can be transformed
    while (ptr1 < str1.length()
           && ptr2 < str2.length()) {
        // If both pointers point to same
        // characters increment them
        if (str1[ptr1] == str2[ptr2]) {
            ptr1++;
            ptr2++;
        }
  
        // If the letters don't match check
        // if we can find it in string C
        else {
  
            // If the letter is available in
            // string str3, decrement it's
            // frequency & increment the ptr2
            if (freq[str3[ptr2]] > 0) {
  
                freq[str3[ptr2]]--;
                ptr2++;
            }
  
            // If letter isn't present in str3[]
            // set the flag to false and break
            else {
                flag = false;
                break;
            }
        }
    }
  
    // If the flag is true and both pointers
    // points to their end of respective strings
    // then it is possible to transformed str1
    // into str2, otherwise not.
    if (flag && ptr1 == str1.length()
        && ptr2 == str2.length()) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
}
  
// Driver Code
int main()
{
    string str1 = "abyzfe";
    string str2 = "abcdeyzf";
    string str3 = "popode";
  
    // Function Call
    convertString(str1, str2, str3);
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program of the above approach
  
# Function to check whether str1 can
# be transformed to str2
def convertString(str1, str2, str3):
      
    # To store the frequency of
    # characters of string str3
    freq = {}
      
    for i in range(len(str3)):
        if(freq.get(str3[i]) == None):
            freq[str3[i]] = 1
        else:
            freq.get(str3[i], 1)
  
    # Declare two pointers & flag
    ptr1 = 0
    ptr2 = 0;
    flag = True
  
    # Traverse both the string and
    # check whether it can be transformed
    while (ptr1 < len(str1) and 
           ptr2 < len(str2)):
          
        # If both pointers point to same
        # characters increment them
        if (str1[ptr1] == str2[ptr2]):
            ptr1 += 1
            ptr2 += 1
  
        # If the letters don't match check
        # if we can find it in string C
        else:
              
            # If the letter is available in
            # string str3, decrement it's
            # frequency & increment the ptr2
            if (freq[str3[ptr2]] > 0):
                freq[str3[ptr2]] -= 1
                ptr2 += 1
  
            # If letter isn't present in str3[]
            # set the flag to false and break
            else:
                flag = False
                break
  
    # If the flag is true and both pointers
    # points to their end of respective strings
    # then it is possible to transformed str1
    # into str2, otherwise not.
    if (flag and ptr1 == len(str1) and
                 ptr2 == len(str2)):
        print("YES")
    else:
        print("NO")
  
# Driver Code
if __name__ == '__main__':
      
    str1 = "abyzfe"
    str2 = "abcdeyzf"
    str3 = "popode"
  
    # Function Call
    convertString(str1, str2, str3)
  
# This code is contributed by Bhupendra_Singh

chevron_right


Output:

NO

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Recommended Posts:



If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : bgangwar59

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.