Check if a string can be obtained by rotating another string 2 places
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.
[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:
- 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
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)
Similar Reads
Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str
9 min read
Javascript Program to Check if a string can be obtained by rotating another string 2 places
Given two strings, the task is to find if a string can be obtained by rotating another string in two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwiseAsked in: Amazon Int
2 min read
Javascript Program to Check if a string can be obtained by rotating another string d places
Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str
4 min read
Check if a string can be obtained by appending subsequences of another string
Given two strings str1 and str2 of lengths N and M respectively, the task is to check if str2 can be formed by appending subsequences of str1 multiple times. If possible, print the minimum number of append operations required. Otherwise, print -1. Examples: Input: str1 = "abb", str2 = "ababbbbb"Outp
8 min read
Check if a string can be transformed to another by sorting substrings
Given two strings str1 and str2, each of length N and consisting of lowercase English alphabets only, the task is to check if string str1 can be transformed to string str2 by performing the following operations any number of times. Choose a non-empty substring in str1 and sort it in-place lexicograp
7 min read
Check if string S1 can be formed using repeated insertions of another string S2
Given two strings S1 and S2 consisting of unique characters, the task is to check S1 can be formed by repeated insertions of string S2. Input: S1 = "aabb", S2 = "ab"Output: YesExplanation: the mentioned string can be obtained after series of moves: Insert string "ab" in an empty string. Current stri
7 min read
Check if a string can be made equal to another string by swapping or replacement of characters
Given two strings S1 and S2, the task is to check if string S1 can be made equal to string S2 by swapping any pair of characters replacing any character in the string S1. If it is possible to make the string S1 equal to S2, then print "Yes". Otherwise, print "No". Examples: Input: S1 = âabcâ, S2 = â
8 min read
Check if one string can be converted to another
Given two strings str and str1, the task is to check whether one string can be converted to other by using the following operation: Convert all the presence of a character by a different character. For example, if str = "abacd" and operation is to change character 'a' to 'k', then the resultant str
8 min read
POTD Solutions | 12 Novâ 23 | Check if string is rotated by two places
View all POTD Solutions Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Strings but will also help you build up problem-solving
7 min read
Check if a string is a scrambled form of another string
Given two strings s1 and s2 of equal length, the task is to determine if s2 is a scrambled version of s1.A scrambled string is formed by recursively splitting the string into two non-empty substrings and rearranging them randomly (s = x + y or s = y + x) and then recursively scramble the two substri
15+ min read