Skip to content
Related Articles

Related Articles

Check if a String can be converted to another by inserting character same as both neighbours

View Discussion
Improve Article
Save Article
  • Last Updated : 05 Oct, 2022
View Discussion
Improve Article
Save Article

Given 2 strings A and B . The task is to check if A can be converted into B by performing the following operation any number of times :

  • Choose an index from 0 to N – 2 (suppose N is the length of A). If the character at ith index is equal to the character at (i + 1 )th index, then insert the same character between the ith and (i + 1)th index.

Examples:

Input: A = “abbaac”, B = “abbbbaaac”
Output: YES
Explanation: A can be converted into B by performing the operations as follows:

  • Insert b between 2nd and 3rd characters of A. ( A becomes abbbaac )
  • Insert b between 2nd and 3rd characters of A.( A becomes abbbbaac )
  • Insert a between 6th and 7th characters of A. ( A becomes abbbbaaac )

Input: A = “xyzz”, B = “xyyzz”
Output: NO

Approach: The given problem can be solved by applying the concept of Run Length Encoding on given strings. For example, strings in 1st example can be encoded as follows :

A = {(a, 1), (b, 2), (a, 2), (c, 1)}
B = {(a, 1), (b, 4), (a, 3), (c, 1)}

Let’s generalize the encoding of 2 strings as :

A = {(a1, x1), (a2, x2), (a3, x3)…..(aN, xN)}
B = {(b1, y1), (b2, y2), (b3, y3)….(bM, yM)}

Now, A can be made equal to B, if the following 3 conditions are satisfied:

  • N = M
  • ai = bi, for i = 1, 2, 3….N
  • Either (xi  = yi ) or (xi  <  yi and xi ≥ 2) for i = 1, 2, 3….N

So, the problem can be solved easily by following the below steps:

  • Apply Run Length Encoding on both strings.
  • Check if the encodings of the strings satisfy above mentioned 3 conditions.

Below is the implementation for the above approach:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
void runLengthEncoding(string S, vector<pair<char, int> >& V)
{
    int count = 1;
    for (int i = 1; i < S.length(); i++) {
        if (S[i] != S[i - 1]) {
            V.push_back({ S[i - 1], count });
            count = 0;
        }
        count++;
    }
    V.push_back({ S.back(), count });
}
 
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
bool isPossible(string A, string B)
{
 
    // Declaring vectors V1 and V2 to store
    // Run Length Encoding of Strings A and B
    vector<pair<char, int> > V1, V2;
    runLengthEncoding(A, V1);
    runLengthEncoding(B, V2);
 
    // Checking for 1st condition
    if (V1.size() != V2.size()) {
        return false;
    }
 
    for (int i = 0; i < V1.size(); i++) {
        // Checking for second condition
        if (V1[i].first != V2[i].first) {
            return false;
        }
 
        // Checking for third condition
        if (!(V1[i].second == V2[i].second || (V1[i].second < V2[i].second && V1[i].second >= 2))) {
            return false;
        }
    }
 
    // If all three conditions are
    // satisfied, return true
    return true;
}
 
// Driver Code
int main()
{
    string A = "abbaac";
    string B = "abbbbaaac";
 
    // Function Call
    bool answer = isPossible(A, B);
    if (answer == 1) {
        cout << "YES" << endl;
    }
    else {
        cout << "NO" << endl;
    }
}

Python3




# Python code for the above approach
 
# Function to perform Run Length Encoding
# on a string S and store that
# in a vector V
def runLengthEncoding(S, V):
    count = 1
    for i in range(1, len(S)):
        if S[i] != S[i - 1]:
            V.append((S[i - 1], count))
            count = 0
        count += 1
    V.append((S[-1], count))
 
# Function to Check if a string can be
# converted into another by performing
# the given operation any number of times
 
 
def isPossible(A, B):
    # Declaring vectors V1 and V2 to store
    # Run Length Encoding of Strings A and B
    V1 = []
    V2 = []
    runLengthEncoding(A, V1)
    runLengthEncoding(B, V2)
 
    # Checking for 1st condition
    if len(V1) != len(V2):
        return False
 
    for i in range(len(V1)):
        # Checking for second condition
        if V1[i][0] != V2[i][0]:
            return False
 
        # Checking for third condition
        if not (V1[i][1] == V2[i][1] or (V1[i][1] < V2[i][1] and V1[i][1] >= 2)):
            return False
 
        # If all three conditions are satisfied, return true
        return True
 
# Driver Code
if __name__ == '__main__':
    A = "abbaac"
    B = "abbbbaaac"
    answer = isPossible(A, B)
    print("YES") if answer else print("NO")
 
# This code is contributed by Tapesh(tapeshdua420)

Output

YES

Time Complexity: O(M + N), where M and N are lengths of string A and B respectively
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!