Check if a string can be obtained by rotating another string 2 places (original) (raw)

Last Updated : 18 Jul, 2024

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.

Try It Yourselfredirect icon

Table of Content

[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

class Solution { public boolean 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.equals(str2);
    }

    // Initialize strings to store the clockwise and
    // anti-clockwise rotations of str2.
    String clockRot = "";
    String anticlockRot = "";
    int len = str2.length();

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

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

    // Check if either the clockwise or anti-clockwise
    // rotation of str2 is equal to str1, and return the
    // result.
    return str1.equals(clockRot)
        || str1.equals(anticlockRot);
}

public static void main(String[] args)
{
    Solution solution = new Solution();

    String str1 = "amazon";
    String str2 = "azonam";
    System.out.println(
        solution.isRotated(str1, str2)); // Output: true

    str1 = "amazon";
    str2 = "onamaz";
    System.out.println(
        solution.isRotated(str1, str2)); // Output: true
}

}

Python

def isRotated(str1, str2): # Check if the lengths of the two strings are # not equal, return False if they are not. if len(str1) != len(str2): return False

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

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

# Store the anti-clockwise rotation of str2
# by concatenating the last 2 characters to the beginning.
anticlock_rot = str2[-2:] + str2[:-2]

# Store the clockwise rotation of str2 by concatenating
# the first 2 characters to the end.
clock_rot = str2[2:] + str2[:2]

# Check if either the clockwise or anti-clockwise 
# rotation of str2 is equal to str1, and return 
# the result.
return str1 == clock_rot or str1 == anticlock_rot

if name == "main": str1 = "amazon" str2 = "azonam" print(isRotated(str1, str2))

str1 = "amazon"
str2 = "onamaz"
print(isRotated(str1, str2))  

C#

using System; public class Solution { public 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 clockRot = "";
    string anticlockRot = "";
    int len = str2.Length;

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

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

    // Check if either the clockwise or anti-clockwise
    // rotation of str2 is equal to str1, and return the
    // result.
    return str1 == clockRot || str1 == anticlockRot;
}

static void Main(string[] args)
{
    Solution solution = new Solution();

    string str1 = "amazon";
    string str2 = "azonam";
    Console.WriteLine(solution.IsRotated(str1, str2));

    str1 = "amazon";
    str2 = "onamaz";
    Console.WriteLine(solution.IsRotated(str1, str2));
}

}

JavaScript

function isRotated(str1, 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.
let clockRot = "";
let anticlockRot = "";
const len = str2.length;

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

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

// Check if either the clockwise or anti-clockwise
// rotation of str2 is equal to str1, and return the result.
return str1 === clockRot || str1 === anticlockRot;

}

// Driver code console.log(isRotated("amazon", "azonam")); console.log(isRotated("amazon", "onamaz"));

`

**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:

**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

class Solution { public boolean isRotated(String str1, String str2) { int n = str1.length(); boolean 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.charAt(i)
            != str2.charAt((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.charAt((i + 2) % n)
            != str2.charAt(i)) {
            anticlockwise
                = false; // not rotated anticlockwise
            break;
        }
    }

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

public static void main(String[] args)
{
    Solution solution = new Solution();

    String str1 = "amazon";
    String str2 = "azonam";
    System.out.println(solution.isRotated(str1, str2));

    str1 = "amazon";
    str2 = "onamaz";
    System.out.println(solution.isRotated(str1, str2));
}

}

Python

def isRotated(str1, str2): n = len(str1) clockwise, anticlockwise = True, True

# Check if str2 can be obtained by rotating str1
# clockwise by 2 places
for i in range(n):
    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 i in range(n):
    if str1[(i + 2) % n] != str2[i]:

       # not rotated anticlockwise
        anticlockwise = False
        break

# if any of both is true, return true
return clockwise or anticlockwise

if name == "main": str1 = "amazon" str2 = "azonam" print(isRotated(str1, str2))

str1 = "amazon"
str2 = "onamaz"
print(isRotated(str1, str2))

C#

using System;

public class Solution { public bool IsRotated(string str1, string str2) { 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 || anticlockwise;
}

static void Main(string[] args)
{
    Solution solution = new Solution();

    string str1 = "amazon";
    string str2 = "azonam";
    Console.WriteLine(solution.IsRotated(str1, str2));

    str1 = "amazon";
    str2 = "onamaz";
    Console.WriteLine(solution.IsRotated(str1, str2));
}

}

JavaScript

function isRotated(str1, str2) { const n = str1.length; let clockwise = true, anticlockwise = true;

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

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

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

}

// Driver code console.log(isRotated("amazon", "azonam")); console.log(isRotated("amazon", "onamaz"));

`

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