Check if one string can be converted to other using given operation
Last Updated :
30 Sep, 2023
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++
// 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;
}
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
<script>
// Javascript implementation of above
// approach
// Function that prints whether
// is it possible to make a
// string equal to T by
// performing given operations
function twoStringsEquality(s, t)
{
var n = s.length;
var dp = Array.from(Array(n), ()=>Array(n+1).fill(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 (var i = n - 1; i > 0; i--) {
for (var 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;
}
}
}
var ans = false;
for (var 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)
document.write( "Yes" + "<br>");
else
document.write( "No" + "<br>");
}
// Driver Code
var S = "abab";
var T = "baab";
twoStringsEquality(S, T);
// This code is contributed by rutvik_56.
</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++
// 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<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<Integer> 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<Integer> 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)
Similar Reads
Converting one string to other using append and delete last operations Given an integer k and two strings str1 and str2 determine whether or not we can convert str1 to str2 by performing exactly k of the below operations on str1. Append a lowercase English alphabetic letter to the end of the str1. Delete the last character in str1 (Performing this operation on an empty
7 min read
Check if a string can be converted to another given string by removal of a substring Given two strings S and T of length N and M respectively, the task is to check if the string S can be converted to the string T by removing at most one substring of the string S. If found to be true, then print âYESâ. Otherwise, print âNOâ. Example: Input: S = âabcdefâ, T = âabcâ Output: YES Explana
7 min read
Check if one string can be converted to another Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation: Convert all the presence of a character by a different character. For example, if str = "abacd" and operation is to change character 'a' to 'k', then the resultant str
8 min read
Check if X can be converted to Y by converting to 3 * (X / 2) or X - 1 in each operation Given two positive integers X and Y, the task is to check if X can be converted to Y or not by repeatedly changing the value of X to (3 * X / 2) (if X is even) or (X - 1). If it is possible to convert X into Y, then print "Yes". Otherwise, print "No". Examples: Input: X = 6, Y = 8Output: YesExplanat
5 min read
Check if it is possible to make all strings of A[] equal to B[] using given operations Consider two arrays, A[] and B[], each containing N strings. These strings are composed solely of digits ranging from 0 to 9. Then your task is to output YES or NO, by following that all the strings of A[] can be made equal to B[] for each i (1 <= i <= N) in at most K cost. The following opera
9 min read