# 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 character 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++

 `// C++ implementation of above` `// approach` `#include ` `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 > 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;` `}`

## Java

 `// 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`

## Python3

 `# 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    `

## C#

 `// 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`

## Javascript

 ``

Output

```Yes

```

Time Complexity: O(N2)

Auxiliary Space: O(N2)

Efficient approach : Space optimization

In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.

Implementation steps:

• Create a 1D vector dp of size large+1.
• Set a base case by initializing the values of DP .
• Now iterate over subproblems by the help of nested loop and get the current value from previous computations.
• Now Create a temporary 1d vector temp used to store the current values from previous computations.
• After every iteration assign the value of temp to dp for further iteration.
• Initialize a variable ans to store the final answer and update it by iterating through the Dp.
• At last return and print the final answer stored in ans .

Implementation:

## C++

 `// C++ implementation of above` `// approach` `#include ` `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<``int``> dp(n + 1, 0);`   `    ``// Base case, if we put the` `    ``// last character at front` `    ``// of A` `    ``if` `(s[n - 1] == t[0])` `        ``dp[1] = 1;`   `    ``// Base case, if we put the` `    ``// last character at back` `    ``// of A` `    ``if` `(s[n - 1] == t[n - 1])` `        ``dp[0] = 1;`   `    ``for` `(``int` `i = n - 1; i > 0; i--) {` `        ``vector<``int``> temp(n + 1, 0);` `        ``for` `(``int` `j = 0; j <= n - i; j++) {`   `            ``// Condition if current` `            ``// sequence is matchable` `            ``if` `(dp[j]) {` `                ``// Condition for front` `                ``// move to (i - 1)th` `                ``// character` `                ``if` `(s[i - 1] == t[j])` `                    ``temp[j + 1] = 1;`   `                ``// Condition for back` `                ``// move to (i - 1)th` `                ``// character` `                ``if` `(s[i - 1] == t[i + j - 1])` `                    ``temp[j] = 1;` `            ``}` `        ``}` `        ``dp = temp;` `    ``}`   `    ``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[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;` `}`

## Java

 `import` `java.util.*;`   `class` `Main` `{` `  `  `    ``// 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();`   `        ``List dp = ``new` `ArrayList<>(Collections.nCopies(n + ``1``, ``0``));`   `        ``// Base case, if we put the` `        ``// last character at front` `        ``// of A` `        ``if` `(s.charAt(n - ``1``) == t.charAt(``0``))` `            ``dp.set(``1``, ``1``);`   `        ``// Base case, if we put the` `        ``// last character at back` `        ``// of A` `        ``if` `(s.charAt(n - ``1``) == t.charAt(n - ``1``))` `            ``dp.set(``0``, ``1``);`   `        ``for` `(``int` `i = n - ``1``; i > ``0``; i--) {` `            ``List temp = ``new` `ArrayList<>(Collections.nCopies(n + ``1``, ``0``));` `            ``for` `(``int` `j = ``0``; j <= n - i; j++) {`   `                ``// Condition if current` `                ``// sequence is matchable` `                ``if` `(dp.get(j) == ``1``) {` `                    ``// Condition for front` `                    ``// move to (i - 1)th` `                    ``// character` `                    ``if` `(s.charAt(i - ``1``) == t.charAt(j))` `                        ``temp.set(j + ``1``, ``1``);`   `                    ``// Condition for back` `                    ``// move to (i - 1)th` `                    ``// character` `                    ``if` `(s.charAt(i - ``1``) == t.charAt(i + j - ``1``))` `                        ``temp.set(j, ``1``);` `                ``}` `            ``}` `            ``dp = temp;` `        ``}`   `        ``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.get(i) == ``1``) {` `                ``ans = ``true``;` `                ``break``;` `            ``}` `        ``}`   `        ``// Print final` `        ``// answer` `        ``if` `(ans == ``true``)` `            ``System.out.println(``"Yes"``);` `        ``else` `            ``System.out.println(``"No"``);` `    ``}`   `    ``// Driver Code` `    ``public` `static` `void` `main(String[] args) {` `        ``String S = ``"abab"``;`   `        ``String T = ``"baab"``;`   `        ``twoStringsEquality(S, T);` `    ``}` `}`

## Python3

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

## C#

 `using` `System;` `using` `System.Collections.Generic;`   `public` `class` `GFG {` `  ``// Function that prints whether` `// is it possible to make a` `// string equal to T by` `// performing given operations` `public` `static` `void` `TwoStringsEquality(``string` `s, ``string` `t) {` `    ``int` `n = s.Length;`   `    ``List<``int``> dp = ``new` `List<``int``>(``new` `int``[n + 1]);`   `    ``// Base case, if we put the` `    ``// last character at front` `    ``// of A` `    ``if` `(s[n - 1] == t[0])` `        ``dp[1] = 1;`   `    ``// Base case, if we put the` `    ``// last character at back` `    ``// of A` `    ``if` `(s[n - 1] == t[n - 1])` `        ``dp[0] = 1;`   `    ``for` `(``int` `i = n - 1; i > 0; i--) {` `        ``List<``int``> temp = ``new` `List<``int``>(``new` `int``[n + 1]);` `        ``for` `(``int` `j = 0; j <= n - i; j++) {`   `            ``// Condition if current` `            ``// sequence is matchable` `            ``if` `(dp[j] == 1) {` `                ``// Condition for front` `                ``// move to (i - 1)th` `                ``// character` `                ``if` `(s[i - 1] == t[j])` `                    ``temp[j + 1] = 1;`   `                ``// Condition for back` `                ``// move to (i - 1)th` `                ``// character` `                ``if` `(s[i - 1] == t[i + j - 1])` `                    ``temp[j] = 1;` `            ``}` `        ``}` `        ``dp = temp;` `    ``}`   `    ``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[i] == 1) {` `            ``ans = ``true``;` `            ``break``;` `        ``}` `    ``}`   `    ``// Print final` `    ``// answer` `    ``if` `(ans == ``true``)` `        ``Console.WriteLine(``"Yes"``);` `    ``else` `        ``Console.WriteLine(``"No"``);` `}`   `// Driver Code` `public` `static` `void` `Main() {` `    ``string` `S = ``"abab"``;`   `    ``string` `T = ``"baab"``;`   `    ``TwoStringsEquality(S, T);` `}`   `}`

## Javascript

 `// Function that prints whether` `// it is possible to make a` `// string equal to T by` `// performing given operations` `function` `twoStringsEquality(s, t) {` `    ``const n = s.length;`   `    ``let dp = ``new` `Array(n + 1).fill(0);`   `    ``// Base case, if we put the` `    ``// last character at front` `    ``// of A` `    ``if` `(s[n - 1] === t[0]) {` `        ``dp[1] = 1;` `    ``}`   `    ``// Base case, if we put the` `    ``// last character at back` `    ``// of A` `    ``if` `(s[n - 1] === t[n - 1]) {` `        ``dp[0] = 1;` `    ``}`   `    ``for` `(let i = n - 1; i > 0; i--) {` `        ``const temp = ``new` `Array(n + 1).fill(0);` `        ``for` `(let j = 0; j <= n - i; j++) {`   `            ``// Condition if current` `            ``// sequence is matchable` `            ``if` `(dp[j]) {` `                ``// Condition for front` `                ``// move to (i - 1)th` `                ``// character` `                ``if` `(s[i - 1] === t[j]) {` `                    ``temp[j + 1] = 1;` `                ``}`   `                ``// Condition for back` `                ``// move to (i - 1)th` `                ``// character` `                ``if` `(s[i - 1] === t[i + j - 1]) {` `                    ``temp[j] = 1;` `                ``}` `            ``}` `        ``}` `        ``dp = temp;` `    ``}`   `    ``let ans = ``false``;`   `    ``for` `(let i = 0; i <= n; i++) {` `        ``// Condition if it is` `        ``// possible to make` `        ``// string A equal to` `        ``// string T` `        ``if` `(dp[i] === 1) {` `            ``ans = ``true``;` `            ``break``;` `        ``}` `    ``}`   `    ``// Print final` `    ``// answer` `    ``if` `(ans) {` `        ``console.log(``"Yes"``);` `    ``} ``else` `{` `        ``console.log(``"No"``);` `    ``}` `}`   `// Driver Code` `const S = ``"abab"``;` `const T = ``"baab"``;` `twoStringsEquality(S, T);`   `// This code is contributed by Dwaipayan Bandyopadhyay`

Output:

`Yes`

Time Complexity: O(N^2)

Auxiliary Space: O(N)

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!