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.
- Delete the first character of S and add it at the front of A.
- 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.
- 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.
- 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.
- 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++
#include <bits/stdc++.h>
using namespace std;
void twoStringsEquality(string s,
string t)
{
int n = s.length();
vector<vector< int > > dp(
n, vector< int >(
n + 1, 0));
if (s[n - 1] == t[0])
dp[n - 1][1] = 1;
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++) {
if (dp[i][j]) {
if (s[i - 1] == t[j])
dp[i - 1][j + 1] = 1;
if (s[i - 1] == t[i + j - 1])
dp[i - 1][j] = 1;
}
}
}
bool ans = false ;
for ( int i = 0; i <= n; i++) {
if (dp[0][i] == 1) {
ans = true ;
break ;
}
}
if (ans == true )
cout << "Yes"
<< "\n" ;
else
cout << "No"
<< "\n" ;
}
int main()
{
string S = "abab" ;
string T = "baab" ;
twoStringsEquality(S, T);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void twoStringsEquality(String s,
String t)
{
int n = s.length();
int [][]dp = new int [n][n + 1 ];
if (s.charAt(n - 1 ) == t.charAt( 0 ))
dp[n - 1 ][ 1 ] = 1 ;
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++)
{
if (dp[i][j] > 0 )
{
if (s.charAt(i - 1 ) ==
t.charAt(j))
dp[i - 1 ][j + 1 ] = 1 ;
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++)
{
if (dp[ 0 ][i] == 1 )
{
ans = true ;
break ;
}
}
if (ans == true )
System.out.print( "Yes" + "\n" );
else
System.out.print( "No" + "\n" );
}
public static void main(String[] args)
{
String S = "abab" ;
String T = "baab" ;
twoStringsEquality(S, T);
}
}
|
Python3
def twoStringsEquality(s, t):
n = len (s)
dp = [[ 0 for i in range (n + 1 )]
for i in range (n)]
if (s[n - 1 ] = = t[ 0 ]):
dp[n - 1 ][ 1 ] = 1
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 ):
if (dp[i][j]):
if (s[i - 1 ] = = t[j]):
dp[i - 1 ][j + 1 ] = 1
if (s[i - 1 ] = = t[i + j - 1 ]):
dp[i - 1 ][j] = 1
ans = False
for i in range (n + 1 ):
if (dp[ 0 ][i] = = 1 ):
ans = True
break
if (ans = = True ):
print ( "Yes" )
else :
print ( "No" )
if __name__ = = '__main__' :
S = "abab"
T = "baab"
twoStringsEquality(S, T)
|
C#
using System;
class GFG{
static void twoStringsEquality(String s,
String t)
{
int n = s.Length;
int [,]dp = new int [n, n + 1];
if (s[n - 1] == t[0])
dp[n - 1, 1] = 1;
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++)
{
if (dp[i, j] > 0)
{
if (s[i - 1] == t[j])
dp[i - 1, j + 1] = 1;
if (s[i - 1] == t[i + j - 1])
dp[i - 1, j] = 1;
}
}
}
bool ans = false ;
for ( int i = 0; i <= n; i++)
{
if (dp[0, i] == 1)
{
ans = true ;
break ;
}
}
if (ans == true )
Console.Write( "Yes" + "\n" );
else
Console.Write( "No" + "\n" );
}
public static void Main(String[] args)
{
String S = "abab" ;
String T = "baab" ;
twoStringsEquality(S, T);
}
}
|
Javascript
<script>
function twoStringsEquality(s, t)
{
var n = s.length;
var dp = Array.from(Array(n), ()=>Array(n+1).fill(0));
if (s[n - 1] == t[0])
dp[n - 1][1] = 1;
if (s[n - 1] == t[n - 1])
dp[n - 1][0] = 1;
for ( var i = n - 1; i > 0; i--) {
for ( var j = 0; j <= n - i; j++) {
if (dp[i][j]) {
if (s[i - 1] == t[j])
dp[i - 1][j + 1] = 1;
if (s[i - 1] == t[i + j - 1])
dp[i - 1][j] = 1;
}
}
}
var ans = false ;
for ( var i = 0; i <= n; i++) {
if (dp[0][i] == 1) {
ans = true ;
break ;
}
}
if (ans == true )
document.write( "Yes" + "<br>" );
else
document.write( "No" + "<br>" );
}
var S = "abab" ;
var T = "baab" ;
twoStringsEquality(S, T);
</script>
|
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++
#include <bits/stdc++.h>
using namespace std;
void twoStringsEquality(string s,
string t)
{
int n = s.length();
vector< int > dp(n + 1, 0);
if (s[n - 1] == t[0])
dp[1] = 1;
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++) {
if (dp[j]) {
if (s[i - 1] == t[j])
temp[j + 1] = 1;
if (s[i - 1] == t[i + j - 1])
temp[j] = 1;
}
}
dp = temp;
}
bool ans = false ;
for ( int i = 0; i <= n; i++) {
if (dp[i] == 1) {
ans = true ;
break ;
}
}
if (ans == true )
cout << "Yes"
<< "\n" ;
else
cout << "No"
<< "\n" ;
}
int main()
{
string S = "abab" ;
string T = "baab" ;
twoStringsEquality(S, T);
return 0;
}
|
Java
import java.util.*;
class Main
{
static void twoStringsEquality(String s, String t) {
int n = s.length();
List<Integer> dp = new ArrayList<>(Collections.nCopies(n + 1 , 0 ));
if (s.charAt(n - 1 ) == t.charAt( 0 ))
dp.set( 1 , 1 );
if (s.charAt(n - 1 ) == t.charAt(n - 1 ))
dp.set( 0 , 1 );
for ( int i = n - 1 ; i > 0 ; i--) {
List<Integer> temp = new ArrayList<>(Collections.nCopies(n + 1 , 0 ));
for ( int j = 0 ; j <= n - i; j++) {
if (dp.get(j) == 1 ) {
if (s.charAt(i - 1 ) == t.charAt(j))
temp.set(j + 1 , 1 );
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++) {
if (dp.get(i) == 1 ) {
ans = true ;
break ;
}
}
if (ans == true )
System.out.println( "Yes" );
else
System.out.println( "No" );
}
public static void main(String[] args) {
String S = "abab" ;
String T = "baab" ;
twoStringsEquality(S, T);
}
}
|
Python3
def twoStringsEquality(s, t):
n = len (s)
dp = [ 0 ] * (n + 1 )
if s[n - 1 ] = = t[ 0 ]:
dp[ 1 ] = 1
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 ):
if dp[j]:
if s[i - 1 ] = = t[j]:
temp[j + 1 ] = 1
if s[i - 1 ] = = t[i + j - 1 ]:
temp[j] = 1
dp = temp
ans = False
for i in range ( 0 , n + 1 ):
if dp[i] = = 1 :
ans = True
break
if ans:
print ( "Yes" )
else :
print ( "No" )
if __name__ = = "__main__" :
S = "abab"
T = "baab"
twoStringsEquality(S, T)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static void TwoStringsEquality( string s, string t) {
int n = s.Length;
List< int > dp = new List< int >( new int [n + 1]);
if (s[n - 1] == t[0])
dp[1] = 1;
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++) {
if (dp[j] == 1) {
if (s[i - 1] == t[j])
temp[j + 1] = 1;
if (s[i - 1] == t[i + j - 1])
temp[j] = 1;
}
}
dp = temp;
}
bool ans = false ;
for ( int i = 0; i <= n; i++) {
if (dp[i] == 1) {
ans = true ;
break ;
}
}
if (ans == true )
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
public static void Main() {
string S = "abab" ;
string T = "baab" ;
TwoStringsEquality(S, T);
}
}
|
Javascript
function twoStringsEquality(s, t) {
const n = s.length;
let dp = new Array(n + 1).fill(0);
if (s[n - 1] === t[0]) {
dp[1] = 1;
}
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++) {
if (dp[j]) {
if (s[i - 1] === t[j]) {
temp[j + 1] = 1;
}
if (s[i - 1] === t[i + j - 1]) {
temp[j] = 1;
}
}
}
dp = temp;
}
let ans = false ;
for (let i = 0; i <= n; i++) {
if (dp[i] === 1) {
ans = true ;
break ;
}
}
if (ans) {
console.log( "Yes" );
} else {
console.log( "No" );
}
}
const S = "abab" ;
const T = "baab" ;
twoStringsEquality(S, T);
|
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!