Check if a String can be converted to another by inserting character same as both neighbours
Last Updated :
21 Oct, 2022
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;
}
}
Java
// Java code for the above approach
import java.util.*;
public class GFG
{
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
static void runLengthEncoding(
String S, ArrayList<pair<Character, Integer> > V)
{
int count = 1;
for (int i = 1; i < S.length(); i++) {
if (S.charAt(i) != S.charAt(i - 1)) {
V.add(new pair<Character, Integer>(
S.charAt(i - 1), count));
count = 0;
}
count++;
}
V.add(new pair<Character, Integer>(
S.charAt(S.length() - 1), count));
}
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
static boolean isPossible(String A, String B)
{
// Declaring vectors V1 and V2 to store
// Run Length Encoding of Strings A and B
ArrayList<pair<Character, Integer> > V1
= new ArrayList<pair<Character, Integer> >();
ArrayList<pair<Character, Integer> > V2
= new ArrayList<pair<Character, Integer> >();
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.get(i).first != V2.get(i).first) {
return false;
}
// Checking for third condition
if (!(V1.get(i).second == V2.get(i).second
|| (V1.get(i).second < V2.get(i).second
&& V1.get(i).second >= 2))) {
return false;
}
}
// If all three conditions are satisfied, return
// true
return true;
}
// Driver Code
public static void main(String[] args)
{
String A = "abbaac";
String B = "abbbbaaac";
// Function Call
boolean answer = isPossible(A, B);
if (answer == true) {
System.out.println("YES");
}
else {
System.out.println("NO");
}
}
}
// Pair Class
class pair<T, U> {
T first;
U second;
public pair(T first, U second)
{
this.first = first;
this.second = second;
}
}
// This code is contributed by Tapesh(tapeshdua420)
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)
C#
// C# implementation
using System;
using System.Collections.Generic;
// represent pair
public class Pair<T, U> {
public Pair() {
}
public Pair(T first, U second) {
this.First = first;
this.Second = second;
}
public T First { get; set; }
public U Second { get; set; }
};
public class GFG{
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
public static void runLengthEncoding(string S, List<Pair<char, int>> V)
{
// Pair<String, int> pair = new Pair<String, int>("test", 2);
int count = 1;
for (int i = 1; i < S.Length; i++) {
if (S[i] != S[i - 1]) {
Pair<char, int> pair = new Pair<char, int>(S[i - 1], count);
V.Add(pair);
count = 0;
}
count++;
}
Pair<char, int> pair2 = new Pair<char, int>(S[S.Length -1], count);
V.Add(pair2);
}
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
public static 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;
var V1 = new List<Pair<char, int>>();
var V2 = new List<Pair<char, int>>();
runLengthEncoding(A, V1);
runLengthEncoding(B, V2);
// Checking for 1st condition
if (V1.Count != V2.Count) {
return false;
}
for (int i = 0; i < V1.Count; 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;
}
static public void Main (){
// Code
string A = "abbaac";
string B = "abbbbaaac";
// Function Call
bool answer = isPossible(A, B);
if (answer == true) {
Console.WriteLine("YES");
}
else {
Console.WriteLine("NO");
}
}
}
// this code is contributed by ksam24000
JavaScript
// Javascript code for the above approach
// Function to perform Run Length Encoding
// on a string S and store that
// in a vector V
function runLengthEncoding(S, V)
{
let count = 1;
for (let i = 1; i < S.length; i++) {
if (S[i] != S[i - 1]) {
V.push({ "first":S[i - 1],
"second":count });
count = 0;
}
count++;
}
V.push({ "first":S[S.length-1],
"second":count });
}
// Function to Check if a string can be
// converted into another by performing
// the given operation any number of times
function isPossible( A, B)
{
// Declaring vectors V1 and V2 to store
// Run Length Encoding of Strings A and B
let V1 = [];
let V2 = [];
runLengthEncoding(A, V1);
runLengthEncoding(B, V2);
// Checking for 1st condition
if (V1.length != V2.length) {
return false;
}
for (let i = 0; i < V1.length; 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
let A = "abbaac";
let B = "abbbbaaac";
// Function Call
let answer = isPossible(A, B);
if (answer == 1) {
console.log("YES");
}
else {
console.log("NO");
}
// This code is contributed by akashish__
Time Complexity: O(M + N), where M and N are lengths of string A and B respectively
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read