Open In App

Check if a string can be obtained by rotating another string 2 places

Last Updated : 18 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given two strings, str1 and str2, the task is to determine if str2 can be obtained by rotating str1 exactly 2 places in either a clockwise or anticlockwise direction.

Examples: 

Input: str1 = “amazon”, str2 = “azonam” 
Output: Yes 
Explanation: Rotating string1 by 2 places in anti-clockwise gives the string2.

Input: str1 = “amazon”, str2 = “onamaz” 
Output: Yes 
Explanation: Rotating string1 by 2 places in clockwise gives the string2.

[Naive Approach] Using String Concatenation – O(n) time and O(n) space

The very basic idea is that first we check if the lengths of str1 and str2 are equal. If they are not, then str2 cannot be a rotated version of str1. Otherwise we’ll create the anticlockwise rotation by moving the last two characters of str1 to the front and we’ll create the clockwise rotation by moving the first two characters of str1 to the end. Now, we can compare both rotated versions with str2. If either matches, return true; otherwise, return false.

Code Implementation:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to check if a string can be obtained by rotating
// another string by exactly 2 places.
bool isRotated(string str1, string str2)
{
    // Check if the lengths of the two strings are not
    // equal, return false if they are not.
    if (str1.length() != str2.length())
        return false;

    // If the length of the strings is less than or equal to
    // 2, simply check if they are equal.
    if (str1.length() <= 2 || str2.length() <= 2)
        return (str1 == str2);

    // Initialize strings to store the clockwise and
    // anti-clockwise rotations of str2.
    string clock_rot = "";
    string anticlock_rot = "";
    int len = str2.length();

    // Store the anti-clockwise rotation of str2 by
    // concatenating the last 2 characters to the beginning.
    anticlock_rot = anticlock_rot + str2.substr(len - 2, 2)
                    + str2.substr(0, len - 2);

    // Store the clockwise rotation of str2 by concatenating
    // the first 2 characters to the end.
    clock_rot
        = clock_rot + str2.substr(2) + str2.substr(0, 2);

    // Check if either the clockwise or anti-clockwise
    // rotation of str2 is equal to str1, and return the
    // result.
    return (str1.compare(clock_rot) == 0
            || str1.compare(anticlock_rot) == 0);
}

// Driver code
int main()
{
    string str1 = "amazon";
    string str2 = "azonam";

    if (isRotated(str1, str2)){
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    
    str1 = "amazon";
    str2 = "onamaz";
    if (isRotated(str1, str2)) {
        cout << "True" << endl;
    } else {
        cout << "False" << endl;
    }
    
    return 0;
}
Java Python C# JavaScript

Output
Yes

Time Complexity: O(n), Time is taken to rotate the string and then compare the string.
Auxiliary Space: O(n), Space for storing clockwise and anticlockwise strings.

[Expected Approach] Direct Comparison Using Modulo Operator – O(n) time and O(1) space

In this approach, Instead of creating new strings, we can directly compare characters in str1 and str2 to check for rotations. By adjusting the indices using the modulo operator, we can simulate the rotation and compare the characters directly. This approach avoids extra space and directly checks if str2 can be obtained by rotating str1.

Below is the Detailed Explanation of above intuition:

  • Check if the lengths of str1 and str2 are equal.
  • Initialize boolean variables clockwise and anticlockwise to true.
  • Compare each character of str1 and str2 for clockwise rotation using str1[i] != str2[(i + 2) % N]:
    • then update the variable clockwise as false and break the loop
  • Compare each character of str1 and str2 for anticlockwise rotation str1[i+2] % N != str2[i]:
    • then update the variable anticlockwise as false and break the loop
  • Return true if either clockwise or anticlockwise is true. Otherwise, return false.

Code Implementation:

C++
// C++ program to check if a string can be obtained by
// rotating another string by exactly 2 places.

#include <bits/stdc++.h>
using namespace std;

// Function to check if a string can be obtained by rotating
// another string by exactly 2 places.
bool isRotated(string str1, string str2)
{
    // Your code here
    int n = str1.length();
    bool clockwise = true, anticlockwise = true;

    // Check if str2 can be obtained by rotating str1
    // clockwise by 2 places
    for (int i = 0; i < n; i++) {
        if (str1[i] != str2[(i + 2) % n]) {
            clockwise = false; // not rotated clockwise
            break;
        }
    }

    // Check if str2 can be obtained by rotating str1
    // anticlockwise by 2 places
    for (int i = 0; i < n; i++) {
        if (str1[(i + 2) % n] != str2[i]) {
            anticlockwise
                = false; // not rotated anticlockwise
            break;
        }
    }

    // if any of both is true, return true
    return clockwise or anticlockwise;
}

// Driver code
int main()
{
    string str1 = "amazon";
    string str2 = "azonam";
    if (isRotated(str1, str2)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }

    str1 = "amazon";
    str2 = "onamaz";
    if (isRotated(str1, str2)) {
        cout << "True" << endl;
    }
    else {
        cout << "False" << endl;
    }

    return 0;
}
Java Python C# JavaScript

Output
Yes

Time Complexity: O(n), Iterating over the string 2 times for comparing both the strings.
Auxiliary Space: O(1)



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg