VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-program-to-check-if-a-string-can-be-obtained-by-rotating-another-string-d-places/

⇱ C++ Program to Check if a string can be obtained by rotating another string d places - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

C++ Program to Check if a string can be obtained by rotating another string d places

Last Updated : 23 Jul, 2025

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:  


Output: 
Yes

 

Time Complexity: O(n), where n represents the size of the given string.
Auxiliary Space: O(n), where n represents the size of the given string.

Approach - String Rotation Check

  • Check if the length of both strings is the same. If not, return false.
  • If d is greater than the length of the string, set d to d % length of string.
  • Create two temporary strings, left_rotate and right_rotate.
  • For left_rotate, copy the first d characters of the original string to the end of left_rotate, and then copy the remaining characters to the beginning of left_rotate.
  • For right_rotate, copy the last d characters of the original string to the beginning of right_rotate, and then copy the remaining characters to the end of right_rotate.
  • Check if either left_rotate or right_rotate is equal to the second string. If either one is equal, return true. Otherwise, return false.

Output
Yes

The time complexity is O(n), where n represents the size of the given string.
The auxiliary space is O(n)

Please refer complete article on Check if a string can be obtained by rotating another string d places for more details!
 

Comment
Article Tags:
Article Tags: