Check if one string can be converted to other using given operation

Given two strings S and T of same length. The task is to determine whether or not we can build a string A(initially empty) equal to string T by performing the below operations.

  1. Delete the first character of S and add it at the front of A.
  2. Delete the first chatacter of S and add it at the back of A.

Examples:

Input: S = “abab” T = “baab”
Output: YES
Explanation:
Add ‘a’ at front of A, then A = “a” and S = “bab”
Add ‘b’ at front of A, then A = “ba” and S = “ab”
Add ‘a’ at back of A, then A = “baa” and S = “b”
Add ‘b’ at back of A, then A = “baab” and S = “”
So we can make string A equal to string T

Input: S = “geeks” T = “Teeks”
Output: NO

Approach: The idea is to use Dynamic Programming to solve this problem.



There are two possible moves for every character( front move or back move ). So, for each character, we will check if it is possible to add the character in the front or back of the new string. If it’s possible, we will move to the next character. If it’s not possible, then the operation will stop at that point and No will be printed.

  1. Firstly we will make a 2D boolean array dp[][] having rows and columns equal to the length of string S, where dp[i][j] = 1 indicates that all characters of string S from index i to n-1 can be placed in the new string A with j front moves such that it becomes equal to string T.
  2. We can traverse string S from the back and for each character update dp[][] in two ways, if we take the (i-1)-th character as a front move or (i-1)-th character as a back move.
  3. Finally, we will check if any value at the 1st row is equal to one or not.

Below is the implementation of the above approach

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of above
// approach
#include <bits/stdc++.h>
using namespace std;
  
// Function that prints whether
// is it possible to make a
// string equal to T by
// performing given operations
void twoStringsEquality(string s,
                        string t)
{
    int n = s.length();
  
    vector<vector<int> > dp(
        n, vector<int>(
               n + 1, 0));
  
    // Base case, if we put the
    // last character at front
    // of A
    if (s[n - 1] == t[0])
        dp[n - 1][1] = 1;
  
    // Base case, if we put the
    // last character at back
    // of A
    if (s[n - 1] == t[n - 1])
        dp[n - 1][0] = 1;
  
    for (int i = n - 1; i > 0; i--) {
        for (int j = 0; j <= n - i; j++) {
  
            // Condition if current
            // sequence is matchable
            if (dp[i][j]) {
                // Condition for front
                // move to (i - 1)th
                // character
                if (s[i - 1] == t[j])
                    dp[i - 1][j + 1] = 1;
  
                // Condition for back
                // move to (i - 1)th
                // character
                if (s[i - 1] == t[i + j - 1])
                    dp[i - 1][j] = 1;
            }
        }
    }
  
    bool ans = false;
  
    for (int i = 0; i <= n; i++) {
        // Condition if it is
        // possible to make
        // string A equal to
        // string T
        if (dp[0][i] == 1) {
            ans = true;
            break;
        }
    }
  
    // Print final
    // answer
    if (ans == true)
        cout << "Yes"
             << "\n";
    else
        cout << "No"
             << "\n";
}
  
// Driver Code
int main()
{
    string S = "abab";
  
    string T = "baab";
  
    twoStringsEquality(S, T);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of above
// approach
import java.util.*;
  
class GFG{
  
// Function that prints whether
// is it possible to make a
// String equal to T by
// performing given operations
static void twoStringsEquality(String s,
                               String t)
{
    int n = s.length();
  
    int [][]dp = new int[n][n + 1];
      
    // Base case, if we put the
    // last character at front
    // of A
    if (s.charAt(n - 1) == t.charAt(0))
        dp[n - 1][1] = 1;
  
    // Base case, if we put the
    // last character at back
    // of A
    if (s.charAt(n - 1) == t.charAt(n - 1))
        dp[n - 1][0] = 1;
  
    for(int i = n - 1; i > 0; i--)
    {
       for(int j = 0; j <= n - i; j++)
       {
             
          // Condition if current
          // sequence is matchable
          if (dp[i][j] > 0)
          {
                
              // Condition for front
              // move to (i - 1)th
              // character
              if (s.charAt(i - 1) ==
                  t.charAt(j))
                  dp[i - 1][j + 1] = 1;
                
              // Condition for back
              // move to (i - 1)th
              // character
              if (s.charAt(i - 1) == 
                  t.charAt(i + j -1))
                  dp[i - 1][j] = 1;
          }
       }
    }
  
    boolean ans = false;
  
    for(int i = 0; i <= n; i++)
    {
          
       // Condition if it is possible
       // to make String A equal to
       // String T
       if (dp[0][i] == 1)
       {
           ans = true;
           break;
       }
    }
      
    // Print final answer
    if (ans == true)
        System.out.print("Yes" + "\n");
    else
        System.out.print("No" + "\n");
}
  
// Driver Code
public static void main(String[] args)
{
    String S = "abab";
    String T = "baab";
  
    twoStringsEquality(S, T);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of above
# approach
  
# Function that prints whether
# is it possible to make a
# equal to T by
# performing given operations
def twoStringsEquality(s, t):
    n = len(s)
  
    dp = [[0 for i in range(n + 1)]
             for i in range(n)]
  
    # Base case, if we put the
    # last character at front
    # of A
    if (s[n - 1] == t[0]):
        dp[n - 1][1] = 1
  
    # Base case, if we put the
    # last character at back
    # of A
    if (s[n - 1] == t[n - 1]):
        dp[n - 1][0] = 1
  
    for i in range(n - 1, -1, -1):
        for j in range(n - i + 1):
  
            # Condition if current
            # sequence is matchable
            if (dp[i][j]):
                  
                # Condition for front
                # move to (i - 1)th
                # character
                if (s[i - 1] == t[j]):
                    dp[i - 1][j + 1] = 1
  
                # Condition for back
                # move to (i - 1)th
                # character
                if (s[i - 1] == t[i + j - 1]):
                    dp[i - 1][j] = 1
  
    ans = False
  
    for i in range(n + 1):
          
        # Condition if it is
        # possible to make
        # A equal to T
        if (dp[0][i] == 1):
            ans = True
            break
  
    # Print final answer
    if (ans == True):
        print("Yes")
    else:
        print("No")
  
# Driver Code
if __name__ == '__main__':
      
    S = "abab"
    T = "baab"
  
    twoStringsEquality(S, T)
      
# This code is contributed by mohit kumar 29    

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of above
// approach
using System;
class GFG{
  
// Function that prints whether
// is it possible to make a
// String equal to T by
// performing given operations
static void twoStringsEquality(String s,
                               String t)
{
    int n = s.Length;
  
    int [,]dp = new int[n, n + 1];
      
    // Base case, if we put the
    // last character at front
    // of A
    if (s[n - 1] == t[0])
        dp[n - 1, 1] = 1;
  
    // Base case, if we put the
    // last character at back
    // of A
    if (s[n - 1] == t[n - 1])
        dp[n - 1, 0] = 1;
  
    for(int i = n - 1; i > 0; i--)
    {
        for(int j = 0; j <= n - i; j++)
        {
                  
            // Condition if current
            // sequence is matchable
            if (dp[i, j] > 0)
            {
                      
                // Condition for front
                // move to (i - 1)th
                // character
                if (s[i - 1] == t[j]) 
                    dp[i - 1, j + 1] = 1;
                      
                // Condition for back
                // move to (i - 1)th
                // character
                if (s[i - 1] == t[i + j - 1])
                    dp[i - 1, j] = 1;
            }
        }
    }
      
    bool ans = false;
  
    for(int i = 0; i <= n; i++)
    {
          
        // Condition if it is possible
        // to make String A equal to
        // String T
        if (dp[0, i] == 1)
        {
            ans = true;
            break;
        }
    }
      
    // Print readonly answer
    if (ans == true)
        Console.Write("Yes" + "\n");
    else
        Console.Write("No" + "\n");
}
  
// Driver Code
public static void Main(String[] args)
{
    String S = "abab";
    String T = "baab";
  
    twoStringsEquality(S, T);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

Yes

Time Complexity: O(N2)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.