Check if two strings can be made equal by reversing a substring of one of the strings - GeeksforGeeks

16 Jun, 2021
Given two strings X and Y of length N, the task is to check if both the strings can be made equal by reversing any substring of X exactly once. If it is possible, then print “Yes”. Otherwise, print “No”.
Examples:
Input: X = “adcbef”, Y = “abcdef”Output: YesExplanation: Strings can be made equal by reversing the substring “dcb” of string X.
Input: X = “126543”, Y = “123456”Output: YesExplanation: Strings can be made equal by reversing the substring “6543” of string X.
Naive Approach: The simplest approach to solve the problem is to reversing every possible substring of the string X and for each reversal, check if both the strings are equal. If found to be true after any reversal, then print “Yes”. Otherwise, print “No”.
Time Complexity: O(N2)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, follow the steps below to solve the problem:
Initialize a variable, say L as -1, to store the first index from the left having unequal characters in the two strings.
Traverse the string X over the range [0, N – 1] using a variable i and if for any index, if the characters in the two strings are found to be unequal, set L = i and break out of the loop.
Initialize a variable, say R as -1, to store the first index from the right having unequal characters in the two strings.
Traverse the string X over the range [N – 1, 0] using the variable i and if for any index, if the characters in the two strings are found to be unequal, set R = i and break out of the loop.
Reverse the characters of the string X over the indices [L, R].
After completing the above steps, check if both the strings are equal or not. If found to be equal, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the strings// can be made equal or not by// reversing a substring of Xbool checkString(string X, string Y){    // Store the first index from    // the left which contains unequal    // characters in both the strings    int L = -1;     // Store the first element from    // the right which contains unequal    // characters in both the strings    int R = -1;     // Checks for the first index from    // left in which characters in both    // the strings are unequal    for (int i = 0; i < X.length(); ++i) {         if (X[i] != Y[i]) {             // Store the current index            L = i;             // Break out of the loop            break;        }    }     // Checks for the first index from    // right in which characters in both    // the strings are unequal    for (int i = X.length() - 1; i > 0; --i) {        if (X[i] != Y[i]) {             // Store the current index            R = i;             // Break out of the loop            break;        }    }     // Reverse the substring X[L, R]    reverse(X.begin() + L,            X.begin() + R + 1);     // If X and Y are equal    if (X == Y) {        cout << "Yes";    }     // Otherwise    else {        cout << "No";    }} // Driver Codeint main(){    string X = "adcbef", Y = "abcdef";     // Function Call    checkString(X, Y);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to check if the Strings// can be made equal or not by// reversing a subString of Xstatic void checkString(String X, String Y){    // Store the first index from    // the left which contains unequal    // characters in both the Strings    int L = -1;     // Store the first element from    // the right which contains unequal    // characters in both the Strings    int R = -1;     // Checks for the first index from    // left in which characters in both    // the Strings are unequal    for (int i = 0; i < X.length(); ++i) {         if (X.charAt(i) != Y.charAt(i)) {             // Store the current index            L = i;             // Break out of the loop            break;        }    }     // Checks for the first index from    // right in which characters in both    // the Strings are unequal    for (int i = X.length() - 1; i > 0; --i) {        if (X.charAt(i) != Y.charAt(i)) {             // Store the current index            R = i;             // Break out of the loop            break;        }    }     // Reverse the subString X[L, R]    X = X.substring(0, L) +      reverse(X.substring(L, R + 1)) +      X.substring(R + 1);     // If X and Y are equal    if (X.equals(Y)) {        System.out.print("Yes");    }     // Otherwise    else {        System.out.print("No");    }}static String reverse(String input) {    char[] a = input.toCharArray();    int l, r = a.length - 1;    for (l = 0; l < r; l++, r--) {        char temp = a[l];        a[l] = a[r];        a[r] = temp;    }    return String.valueOf(a);}   // Driver Codepublic static void main(String[] args){    String X = "adcbef", Y = "abcdef";     // Function Call    checkString(X, Y);}} // This code is contributed by 29AjayKumar
# Python3 program for the above approach # Function to check if the strings# can be made equal or not by# reversing a substring of Xdef checkString(X, Y):     # Store the first index from    # the left which contains unequal    # characters in both the strings    L = -1     # Store the first element from    # the right which contains unequal    # characters in both the strings    R = -1     # Checks for the first index from    # left in which characters in both    # the strings are unequal    for i in range(len(X)):        if (X[i] != Y[i]):             # Store the current index            L = i             # Break out of the loop            break     # Checks for the first index from    # right in which characters in both    # the strings are unequal    for i in range(len(X) - 1, 0, -1):        if (X[i] != Y[i]):                         # Store the current index            R = i             # Break out of the loop            break     X = list(X)         X = X[:L] + X[R  : L - 1 : -1 ] + X[R + 1:]         # If X and Y are equal    if (X == list(Y)):        print("Yes")     # Otherwise    else:        print("No") # Driver Codeif __name__ == "__main__" :     X = "adcbef"    Y = "abcdef"     # Function Call    checkString(X, Y)     # This code is contributed by AnkThon
// C# program for the above approachusing System; class GFG{ // Function to check if the Strings// can be made equal or not by// reversing a subString of Xstatic void checkString(String X, String Y){         // Store the first index from    // the left which contains unequal    // characters in both the Strings    int L = -1;     // Store the first element from    // the right which contains unequal    // characters in both the Strings    int R = -1;     // Checks for the first index from    // left in which characters in both    // the Strings are unequal    for(int i = 0; i < X.Length; ++i)    {        if (X[i] != Y[i])        {                         // Store the current index            L = i;             // Break out of the loop            break;        }    }     // Checks for the first index from    // right in which characters in both    // the Strings are unequal    for(int i = X.Length - 1; i > 0; --i)    {        if (X[i] != Y[i])        {                         // Store the current index            R = i;             // Break out of the loop            break;        }    }     // Reverse the subString X[L, R]    X = X.Substring(0, L) +        reverse(X.Substring(L, R + 1 - L)) +        X.Substring(R + 1);     // If X and Y are equal    if (X.Equals(Y))    {        Console.Write("Yes");    }     // Otherwise    else    {        Console.Write("No");    }} static String reverse(String input){    char[] a = input.ToCharArray();    int l, r = a.Length - 1;         for(l = 0; l < r; l++, r--)    {        char temp = a[l];        a[l] = a[r];        a[r] = temp;    }    return String.Join("",a);}   // Driver Codepublic static void Main(String[] args){    String X = "adcbef", Y = "abcdef";     // Function Call    checkString(X, Y);}} // This code is contributed by Amit Katiyar
<script>       // JavaScript program for the above approach             // Function to check if the Strings      // can be made equal or not by      // reversing a subString of X      function checkString(X, Y) {        // Store the first index from        // the left which contains unequal        // characters in both the Strings        var L = -1;         // Store the first element from        // the right which contains unequal        // characters in both the Strings        var R = -1;         // Checks for the first index from        // left in which characters in both        // the Strings are unequal        for (var i = 0; i < X.length; ++i) {          if (X[i] !== Y[i]) {            // Store the current index            L = i;             // Break out of the loop            break;          }        }         // Checks for the first index from        // right in which characters in both        // the Strings are unequal        for (var i = X.length - 1; i > 0; --i) {          if (X[i] !== Y[i]) {            // Store the current index            R = i;             // Break out of the loop            break;          }        }         // Reverse the subString X[L, R]        X =          X.substring(0, L) +          reverse(X.substring(L, R + 1)) +          X.substring(R + 1);         // If X and Y are equal        if (X === Y) {          document.write("Yes");        }         // Otherwise        else {          document.write("No");        }      }       function reverse(input) {        var a = input.split("");        var l,          r = a.length - 1;         for (l = 0; l < r; l++, r--) {          var temp = a[l];          a[l] = a[r];          a[r] = temp;        }        return a.join("");      }       // Driver Code      var X = "adcbef",        Y = "abcdef";       // Function Call      checkString(X, Y);        </script>
Yes
 
Time Complexity: O(N)Auxiliary Space: O(1)
29AjayKumar
amit143katiyar
ankthon
khushboogoyal499
rdtank
Reverse
substring
two-pointer-algorithm
Searching
Strings
two-pointer-algorithm
Searching
Strings
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Best First Search (Informed Search)
Program to remove vowels from a String
Find whether an array is subset of another array | Added Method 5
Find common elements in three sorted arrays
3 Different ways to print Fibonacci series in Java
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types