Open In App

Check if given Strings can be made equal by inserting at most 1 String

Last Updated : 20 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given two sentences S1 and S2, the task is to check if the sentences can be made equal by inserting at most one sentence(possibly, empty) into any one of the two sentences.

Examples:

Input : S1 = “Start practicing on GeeksforGeeks”, S2 =”Start GeeksforGeeks”   
Output : 
True
Explanation: “practicing on” can be inserted between “Start” and “GeeksforGeeks” in s2 to make it equal to S1.

Input: S1= “New Delhi is capital of INDIA”, S2 = “is capital of”   
Output: 
False

 

Approach: The following observations help in solving the problem:

  • If the sizes of two sentences are equal, but they themselves are not the same, they cannot be made equal.
  • After the longest common prefix and the longest common suffix of the two sentences are removed, if at least one of them is empty, it means that they can be made equal.

The problem can be solved with the help of deques. Follow the steps below to solve the problem:

  • Check if the size of S1 and S2 are equal. If they are equal, do the following:
    • If S1 is equal to S2, return true.
    • Otherwise, return false.
  • Initialize two deques X and Y.
  • Push all words of S1 into X.
  • Push all words of S2 into Y.
  • While the fronts of X and Y are the same, pop from the fronts of both X and Y.
  • While the backs of X and Y are the same, pop from the backs of both X and Y.
  • Check if any one of X or Y is empty. If any of them is empty, return true.
  • Otherwise, return false.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check whether
// two sentences can be made equal
// by inserting at most
// one sentence in one of them
bool areSimilar(string S1, string S2)
{
    // size of sentence S1
    int N = S1.size();
 
    // size of sentence S2
    int M = S2.size();
 
    // check if S1 and S2
    // are of equal sizes
    if (N == M) {
        // if both sentences are
        // the same, return true
        if (S1 == S2)
            return true;
 
        // Otherwise, return false
        return false;
    }
 
    // Declare 2 deques X and Y
    deque<string> X, Y;
 
    // insert ' ' at the end of both
    // sentences so that the last
    // word can be identified
    S1.push_back(' ');
    S2.push_back(' ');
 
    string temp = "";
 
    // traverse the sentence S1
    for (int i = 0; i < N + 1; i++) {
 
        // push temp in deque
        // when a space comes in sentence
        // i.e a word has been formed
        if (S1[i] == ' ') {
            X.push_back(temp);
            temp = "";
        }
        else {
            // temp stores words
            // of the sentence
            temp += S1[i];
        }
    }
 
    // traverse the sentence S1
    for (int i = 0; i < M + 1; i++) {
 
        // push temp in deque
        // when a space comes in sentence
        // i.e a word has been formed
        if (S2[i] == ' ') {
            Y.push_back(temp);
            temp = "";
        }
        else {
            // temp stores words of the sentence
            temp += S2[i];
        }
    }
 
    // check for prefixes of both sentences
    while (X.size() > 0 && Y.size() > 0
           && X.front() == Y.front()) {
 
        // pop the prefix from both
        // deques till they are equal
        X.pop_front();
        Y.pop_front();
    }
 
    // check for suffixes of both sentences
    while (X.size() > 0 && Y.size() > 0
           && X.back() == Y.back()) {
 
        // pop the suffix from both deques
        // till they are equal
        X.pop_back();
        Y.pop_back();
    }
 
    // if any of the deques is empty
    // return true
    if (X.size() == 0 || Y.size() == 0)
        return true;
 
    // if both the deques are
    // not empty return false
    return false;
}
// Driver code
int main()
{
    // Input
    string S1 = "Start practicing on GeeksforGeeks";
    string S2 = "Start GeeksforGeeks";
 
    // function call
    if (areSimilar(S1, S2))
        cout << "True" << endl;
    else
        cout << "False" << endl;
    return 0;
}


Java




import java.util.*;
 
public class Main {
    // Function to check whether
    // two sentences can be made equal
    // by inserting at most
    // one sentence in one of them
    public static boolean areSimilar(String S1, String S2) {
        // size of sentence S1
        int N = S1.length();
 
        // size of sentence S2
        int M = S2.length();
 
        // check if S1 and S2
        // are of equal sizes
        if (N == M) {
            // if both sentences are
            // the same, return true
            if (S1.equals(S2))
                return true;
 
            // Otherwise, return false
            return false;
        }
 
        // Declare 2 deques X and Y
        Deque<String> X = new LinkedList<>();
        Deque<String> Y = new LinkedList<>();
 
        // insert ' ' at the end of both
        // sentences so that the last
        // word can be identified
        S1 += " ";
        S2 += " ";
 
        String temp = "";
 
        // traverse the sentence S1
        for (int i = 0; i < N + 1; i++) {
            // push temp in deque
            // when a space comes in sentence
            // i.e a word has been formed
            if (S1.charAt(i) == ' ') {
                X.addLast(temp);
                temp = "";
            } else {
                // temp stores words
                // of the sentence
                temp += S1.charAt(i);
            }
        }
 
        // traverse the sentence S2
        for (int i = 0; i < M + 1; i++) {
            // push temp in deque
            // when a space comes in sentence
            // i.e a word has been formed
            if (S2.charAt(i) == ' ') {
                Y.addLast(temp);
                temp = "";
            } else {
                // temp stores words of the sentence
                temp += S2.charAt(i);
            }
        }
 
        // check for prefixes of both sentences
        while (!X.isEmpty() && !Y.isEmpty()
                && X.peekFirst().equals(Y.peekFirst())) {
            // pop the prefix from both
            // deques till they are equal
            X.removeFirst();
            Y.removeFirst();
        }
 
        // check for suffixes of both sentences
        while (!X.isEmpty() && !Y.isEmpty()
                && X.peekLast().equals(Y.peekLast())) {
            // pop the suffix from both deques
            // till they are equal
            X.removeLast();
            Y.removeLast();
        }
 
        // if any of the deques is empty
        // return true
        if (X.isEmpty() || Y.isEmpty())
            return true;
 
        // if both the deques are
        // not empty return false
        return false;
    }
 
    // Driver code
    public static void main(String[] args) {
        // Input
        String S1 = "Start practicing on GeeksforGeeks";
        String S2 = "Start GeeksforGeeks";
 
        // function call
        if (areSimilar(S1, S2))
            System.out.println("True");
        else
            System.out.println("False");
    }
}


Python3




# Python3 program for the above approach
from collections import deque
 
# Function to check whether
# two sentences can be made equal
# by inserting at most
# one sentence in one of them
def areSimilar(S1, S2):
     
    S1 = [i for i in S1]
    S2 = [i for i in S2]
     
    # Size of sentence S1
    N = len(S1)
 
    # Size of sentence S2
    M = len(S2)
 
    # Check if S1 and S2
    # are of equal sizes
    if (N == M):
         
        # If both sentences are
        # the same, return True
        if (S1 == S2):
            return True
 
        # Otherwise, return false
        return False
 
    # Declare 2 deques X and Y
    X, Y = deque(), deque()
 
    # Insert ' ' at the end of both
    # sentences so that the last
    # word can be identified
    S1.append(' ')
    S2.append(' ')
 
    temp = ""
 
    # Traverse the sentence S1
    for i in range(N + 1):
         
        # Push temp in deque
        # when a space comes in sentence
        # i.e a word has been formed
        if (S1[i] == ' '):
            X.append(temp)
            temp = ""
        else:
             
            # temp stores words
            # of the sentence
            temp += S1[i]
 
    # Traverse the sentence S1
    for i in range(M + 1):
         
        # Push temp in deque
        # when a space comes in sentence
        # i.e a word has been formed
        if (S2[i] == ' '):
            Y.append(temp)
            temp = ""
        else:
             
            # temp stores words of the sentence
            temp += S2[i]
 
    # Check for prefixes of both sentences
    while (len(X) > 0 and
           len(Y) > 0 and X[0] == Y[0]):
 
        # Pop the prefix from both
        # deques till they are equal
        X.popleft()
        Y.popleft()
 
    # Check for suffixes of both sentences
    while (len(X) > 0 and len(Y) > 0 and
           X[-1] == Y[-1]):
                
        # Pop the suffix from both deques
        # till they are equal
        X.pop()
        Y.pop()
 
    # If any of the deques is empty
    # return True
    if (len(X) == 0 or len(Y) == 0):
        return True
 
    # If both the deques are
    # not empty return false
    return False
 
# Driver code
if __name__ == '__main__':
     
    # Input
    S1 = "Start practicing on GeeksforGeeks"
    S2 = "Start GeeksforGeeks"
 
    # Function call
    if (areSimilar(S1, S2)):
        print("True")
    else:
        print("False")
 
# This code is contributed by mohit kumar 29


C#




using System;
using System.Collections.Generic;
 
class Program
{
    // Function to check whether
    // two sentences can be made equal
    // by inserting at most
    // one sentence in one of them
    static bool AreSimilar(string S1, string S2)
    {
        // size of sentence S1
        int N = S1.Length;
 
        // size of sentence S2
        int M = S2.Length;
 
        // check if S1 and S2
        // are of equal sizes
        if (N == M)
        {
            // if both sentences are
            // the same, return true
            if (S1 == S2)
                return true;
 
            // Otherwise, return false
            return false;
        }
 
        // Declare 2 deques X and Y
        Queue<string> X = new Queue<string>();
        Queue<string> Y = new Queue<string>();
 
        // insert ' ' at the end of both
        // sentences so that the last
        // word can be identified
        S1 += ' ';
        S2 += ' ';
 
        string temp = "";
 
        // traverse the sentence S1
        for (int i = 0; i < N + 1; i++)
        {
 
            // push temp in deque
            // when a space comes in sentence
            // i.e a word has been formed
            if (S1[i] == ' ')
            {
                X.Enqueue(temp);
                temp = "";
            }
            else
            {
                // temp stores words
                // of the sentence
                temp += S1[i];
            }
        }
 
        // traverse the sentence S2
        for (int i = 0; i < M + 1; i++)
        {
 
            // push temp in deque
            // when a space comes in sentence
            // i.e a word has been formed
            if (S2[i] == ' ')
            {
                Y.Enqueue(temp);
                temp = "";
            }
            else
            {
                // temp stores words of the sentence
                temp += S2[i];
            }
        }
 
        // check for prefixes of both sentences
        while (X.Count > 0 && Y.Count > 0
               && X.Peek() == Y.Peek())
        {
 
            // pop the prefix from both
            // deques till they are equal
            X.Dequeue();
            Y.Dequeue();
        }
 
        // check for suffixes of both sentences
        while (X.Count > 0 && Y.Count > 0
               && X.ToArray()[X.Count - 1] == Y.ToArray()[Y.Count - 1])
        {
 
            // pop the suffix from both deques
            // till they are equal
            X.Dequeue();
            Y.Dequeue();
        }
 
        // if any of the deques is empty
        // return true
        if (X.Count == 0 || Y.Count == 0)
            return true;
 
        // if both the deques are
        // not empty return false
        return false;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        // Input
        string S1 = "Start practicing on GeeksforGeeks";
        string S2 = "Start GeeksforGeeks";
 
        // function call
        if (AreSimilar(S1, S2))
            Console.WriteLine("True");
        else
            Console.WriteLine("False");
 
        Console.ReadLine();
    }
}


Javascript




// JavaScript program for the above approach
 
// Function to check whether
// two sentences can be made equal
// by inserting at most
// one sentence in one of them
function areSimilar(S1, S2) {
    S1 = S1.split('');
    S2 = S2.split('');
 
    // Size of sentence S1
    const N = S1.length;
 
    // Size of sentence S2
    const M = S2.length;
 
    // Check if S1 and S2
    // are of equal sizes
    if (N === M) {
 
        // If both sentences are
        // the same, return true
        if (S1.join('') === S2.join('')) {
            return true;
        }
 
        // Otherwise, return false
        return false;
    }
 
    // Declare 2 deques X and Y
    const X = [],
        Y = [];
 
    // Insert ' ' at the end of both
    // sentences so that the last
    // word can be identified
    S1.push(' ');
    S2.push(' ');
 
    let temp = "";
 
    // Traverse the sentence S1
    for (let i = 0; i < N + 1; i++) {
 
        // Push temp in deque
        // when a space comes in sentence
        // i.e a word has been formed
        if (S1[i] === ' ') {
            X.push(temp);
            temp = "";
        } else {
 
            // temp stores words
            // of the sentence
            temp += S1[i];
        }
    }
 
    // Traverse the sentence S1
    for (let i = 0; i < M + 1; i++) {
 
        // Push temp in deque
        // when a space comes in sentence
        // i.e a word has been formed
        if (S2[i] === ' ') {
            Y.push(temp);
            temp = "";
        } else {
 
            // temp stores words of the sentence
            temp += S2[i];
        }
    }
 
    // Check for prefixes of both sentences
    while (X.length > 0 && Y.length > 0 && X[0] === Y[0]) {
 
        // Pop the prefix from both
        // deques till they are equal
        X.shift();
        Y.shift();
    }
 
    // Check for suffixes of both sentences
    while (X.length > 0 && Y.length > 0 && X[X.length - 1] === Y[Y.length - 1]) {
 
        // Pop the suffix from both deques
        // till they are equal
        X.pop();
        Y.pop();
    }
 
    // If any of the deques is empty
    // return true
    if (X.length === 0 || Y.length === 0) {
        return true;
    }
 
    // If both the deques are
    // not empty return false
    return false;
}
 
// Driver code
const S1 = "Start practicing on GeeksforGeeks";
const S2 = "Start GeeksforGeeks";
 
// Function call
if (areSimilar(S1, S2)) {
    console.log("True");
} else {
    console.log("False");
}
 
// Contributed by adityashae15


Output

True

Time Complexity: O(N+M), where N and M are the sizes of S1 and S2 respectively.
Auxiliary Space: O(N+M)

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads