Check if a string can be obtained by rotating another string d places
Last Updated :
17 Mar, 2023
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", str2 = "cdfdawb", d = 6
Output: No
Approach: An approach to solve the same problem has been discussed here. In this article, reversal algorithm is used to rotate the string to the left and to the right in O(n). If any one of the rotations of str1 is equal to str2 then print Yes else print No.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to reverse an array from left
// index to right index (both inclusive)
void ReverseArray(string& arr, int left, int right)
{
char temp;
while (left < right) {
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// Function that returns true if str1 can be
// made equal to str2 by rotating either
// d places to the left or to the right
bool RotateAndCheck(string& str1, string& str2, int d)
{
if (str1.length() != str2.length())
return false;
// Left Rotation string will contain
// the string rotated Anti-Clockwise
// Right Rotation string will contain
// the string rotated Clockwise
string left_rot_str1, right_rot_str1;
bool left_flag = true, right_flag = true;
int str1_size = str1.size();
// Copying the str1 string to left rotation string
// and right rotation string
for (int i = 0; i < str1_size; i++) {
left_rot_str1.push_back(str1[i]);
right_rot_str1.push_back(str1[i]);
}
// Rotating the string d positions to the left
ReverseArray(left_rot_str1, 0, d - 1);
ReverseArray(left_rot_str1, d, str1_size - 1);
ReverseArray(left_rot_str1, 0, str1_size - 1);
// Rotating the string d positions to the right
ReverseArray(right_rot_str1, 0, str1_size - d - 1);
ReverseArray(right_rot_str1, str1_size - d, str1_size - 1);
ReverseArray(right_rot_str1, 0, str1_size - 1);
// Comparing the rotated strings
for (int i = 0; i < str1_size; i++) {
// If cannot be made equal with left rotation
if (left_rot_str1[i] != str2[i]) {
left_flag = false;
}
// If cannot be made equal with right rotation
if (right_rot_str1[i] != str2[i]) {
right_flag = false;
}
}
// If both or any one of the rotations
// of str1 were equal to str2
if (left_flag || right_flag)
return true;
return false;
}
// Driver code
int main()
{
string str1 = "abcdefg";
string str2 = "cdefgab";
// d is the rotating factor
int d = 2;
// In case length of str1 < d
d = d % str1.size();
if (RotateAndCheck(str1, str2, d))
cout << "Yes";
else
cout << "No";
return 0;
}
Java
/*package whatever //do not write package name here */
import java.util.*;
class GFG {
// Helper function to reverse a substring of a string
static void reverseArray(char[] arr, int left, int right) {
while (left < right) {
char temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// Function to check if str1 can be rotated to get str2
static boolean rotateAndCheck(String str1, String str2, int d) {
// Check if both strings have the same length
if (str1.length() != str2.length())
return false;
// Create copies of str1
char[] leftRotStr1 = str1.toCharArray();
char[] rightRotStr1 = str1.toCharArray();
// Initialize flags
boolean leftFlag = true, rightFlag = true;
int str1Size = str1.length();
// Rotate the copies of str1
reverseArray(leftRotStr1, 0, d-1);
reverseArray(leftRotStr1, d, str1Size-1);
reverseArray(leftRotStr1, 0, str1Size-1);
reverseArray(rightRotStr1, 0, str1Size-d-1);
reverseArray(rightRotStr1, str1Size-d, str1Size-1);
// Check if ecopies of str1 is equal to str2
for (int i = 0; i < str1Size; i++) {
if (leftRotStr1[i] != str2.charAt(i)) {
leftFlag = false;
}
if (rightRotStr1[i] != str2.charAt(i)) {
rightFlag = false;
}
}
// Return true if at least one copies is equal
if (leftFlag || rightFlag)
return true;
return false;
}
// Main function
public static void main(String[] args) {
String str1 = "abcdefg";
String str2 = "cdefgab";
int d = 2;
d = d % str1.length();
if (rotateAndCheck(str1, str2, d))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python3
# Python3 implementation of the approach
# Function to reverse an array from left
# index to right index (both inclusive)
def ReverseArray(arr, left, right) :
while (left < right) :
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left += 1;
right -= 1;
# Function that returns true if str1 can be
# made equal to str2 by rotating either
# d places to the left or to the right
def RotateAndCheck(str1, str2, d) :
if (len(str1) != len(str2)) :
return False;
# Left Rotation string will contain
# the string rotated Anti-Clockwise
# Right Rotation string will contain
# the string rotated Clockwise
left_rot_str1 = []; right_rot_str1 = [];
left_flag = True; right_flag = True;
str1_size = len(str1);
# Copying the str1 string to left rotation string
# and right rotation string
for i in range(str1_size) :
left_rot_str1.append(str1[i]);
right_rot_str1.append(str1[i]);
# Rotating the string d positions to the left
ReverseArray(left_rot_str1, 0, d - 1);
ReverseArray(left_rot_str1, d, str1_size - 1);
ReverseArray(left_rot_str1, 0, str1_size - 1);
# Rotating the string d positions to the right
ReverseArray(right_rot_str1, 0, str1_size - d - 1);
ReverseArray(right_rot_str1,
str1_size - d, str1_size - 1);
ReverseArray(right_rot_str1, 0, str1_size - 1);
# Comparing the rotated strings
for i in range(str1_size) :
# If cannot be made equal with left rotation
if (left_rot_str1[i] != str2[i]) :
left_flag = False;
# If cannot be made equal with right rotation
if (right_rot_str1[i] != str2[i]) :
right_flag = False;
# If both or any one of the rotations
# of str1 were equal to str2
if (left_flag or right_flag) :
return True;
return False;
# Driver code
if __name__ == "__main__" :
str1 = list("abcdefg");
str2 = list("cdefgab");
# d is the rotating factor
d = 2;
# In case length of str1 < d
d = d % len(str1);
if (RotateAndCheck(str1, str2, d)) :
print("Yes");
else :
print("No");
# This code is contributed by AnkitRai01
C#
using System;
// C# program to check if a string is two time
// rotation of another string.
public class Test {
static string ReverseArray(char[] arr, int left, int right)
{
char temp;
while (left < right) {
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
return String.Join("",arr);
}
// Method to check if string2 is obtained by
// string 1
public static bool RotateAndCheck(string str1, string str2, int d)
{
if (str1.Length != str2.Length) {
return false;
}
// Left Rotation string will contain
// the string rotated Anti-Clockwise
// Right Rotation string will contain
// the string rotated Clockwise
string left_rot_str1="", right_rot_str1="";
bool left_flag = true, right_flag = true;
int len1 = str1.Length;
// Copying the str1 string to left rotation string
// and right rotation string
for (int i = 0; i < len1; i++) {
left_rot_str1+=str1[i];
right_rot_str1+=str1[i];
}
// Rotating the string d positions to the left
left_rot_str1=ReverseArray(left_rot_str1.ToCharArray(), 0, d - 1);
left_rot_str1=ReverseArray(left_rot_str1.ToCharArray(), d, len1 - 1);
left_rot_str1=ReverseArray(left_rot_str1.ToCharArray(), 0, len1 - 1);
// Rotating the string d positions to the right
right_rot_str1=ReverseArray(right_rot_str1.ToCharArray(), 0, len1 - d - 1);
right_rot_str1=ReverseArray(right_rot_str1.ToCharArray(), len1 - d, len1 - 1);
right_rot_str1=ReverseArray(right_rot_str1.ToCharArray(), 0, len1 - 1);
// Comparing the rotated strings
for (int i = 0; i < len1; i++) {
// If cannot be made equal with left rotation
if (left_rot_str1[i] != str2[i]) {
left_flag = false;
}
// If cannot be made equal with right rotation
if (right_rot_str1[i] != str2[i]) {
right_flag = false;
}
}
// If both or any one of the rotations
// of str1 were equal to str2
if (left_flag || right_flag)
return true;
return false;
}
// Driver code
public static void Main(string[] args)
{
string str1 = "abcdefg";
string str2 = "cdefgab";
// d is the rotating factor
int d = 2;
// In case length of str1 < d
d = d % str1.Length;
Console.WriteLine(RotateAndCheck(str1, str2,d) ? "Yes"
: "No");
}
}
// This code is contributed by Aarti_Rathi
JavaScript
<script>
// JavaScript implementation of the approach
// Function to reverse an array from left
// index to right index (both inclusive)
function ReverseArray(arr, left, right)
{
var temp;
while (left < right)
{
temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
// Function that returns true if str1 can be
// made equal to str2 by rotating either
// d places to the left or to the right
function RotateAndCheck(str1, str2, d)
{
if (str1.length !== str2.length)
return false;
// Left Rotation string will contain
// the string rotated Anti-Clockwise
// Right Rotation string will contain
// the string rotated Clockwise
var left_rot_str1 = [];
var right_rot_str1 = [];
var left_flag = true,
right_flag = true;
var str1_size = str1.length;
// Copying the str1 string to left rotation string
// and right rotation string
for(var i = 0; i < str1_size; i++)
{
left_rot_str1.push(str1[i]);
right_rot_str1.push(str1[i]);
}
// Rotating the string d positions to the left
ReverseArray(left_rot_str1, 0, d - 1);
ReverseArray(left_rot_str1, d, str1_size - 1);
ReverseArray(left_rot_str1, 0, str1_size - 1);
// Rotating the string d positions to the right
ReverseArray(right_rot_str1, 0, str1_size - d - 1);
ReverseArray(right_rot_str1, str1_size - d,
str1_size - 1);
ReverseArray(right_rot_str1, 0, str1_size - 1);
// Comparing the rotated strings
for(var i = 0; i < str1_size; i++)
{
// If cannot be made equal with left rotation
if (left_rot_str1[i] !== str2[i])
{
left_flag = false;
}
// If cannot be made equal with right rotation
if (right_rot_str1[i] !== str2[i])
{
right_flag = false;
}
}
// If both or any one of the rotations
// of str1 were equal to str2
if (left_flag || right_flag)
return true;
return false;
}
// Driver code
var str1 = "abcdefg";
var str2 = "cdefgab";
// d is the rotating factor
var d = 2;
// In case length of str1 < d
d = d % str1.length;
if (RotateAndCheck(str1, str2, d))
document.write("Yes");
else
document.write("No");
// This code is contributed by rdtank
</script>
Time Complexity: O(n), where n represents the size of the string.
Auxiliary Space: O(n), where n represents the size of the string.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 min read