Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
C++ Program to Check if a string can be formed from another string by at most X circular clockwise shifts
Next article icon

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

Last Updated : 24 May, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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; } 

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.
C++
#include <iostream> #include <string>  using namespace std;  bool canRotate(string str1, string str2, int d) {    int n = str1.length();     // Check if the length of both strings is the same    if (n != str2.length()) {        return false;    }     // If d is greater than the length of the string, set d to d % length of string    d = d % n;     // Create temporary strings for left and right rotations    string left_rotate = str1.substr(d) + str1.substr(0, d);    string right_rotate = str1.substr(n - d) + str1.substr(0, n - d);     // Check if either left_rotate or right_rotate is equal to str2    if (left_rotate == str2 || right_rotate == str2) {        return true;    }     return false; }  int main() {    string str1 = "abcdefg";    string str2 = "cdefgab";    int d = 2;     if (canRotate(str1, str2, d)) {        cout << "Yes" << endl;    } else {        cout << "No" << endl;    }     return 0; } 

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!
 


Next Article
C++ Program to Check if a string can be formed from another string by at most X circular clockwise shifts
author
kartik
Improve
Article Tags :
  • Strings
  • C++ Programs
  • C++
  • DSA
  • rotation
  • Reverse
Practice Tags :
  • CPP
  • Reverse
  • Strings

Similar Reads

  • C++ 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 two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Inter
    2 min read
  • C++ Program To Check If A String Is Substring Of Another
    Given two strings s1 and s2, find if s1 is a substring of s2. If yes, return the index of the first occurrence, else return -1. Examples :  Input: s1 = "for", s2 = "geeksforgeeks" Output: 5 Explanation: String "for" is present as a substring of s2. Input: s1 = "practice", s2 = "geeksforgeeks" Output
    4 min read
  • C++ Program to Check if a string can be formed from another string by at most X circular clockwise shifts
    Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a
    3 min read
  • C++ Program to Check if strings are rotations of each other or not | Set 2
    Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples:  Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (lon
    2 min read
  • Check if a string can be formed from another string by at most X circular clockwise shifts
    Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a
    7 min read
  • C++ Program to check if strings are rotations of each other or not
    Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false) Algorithm: areRotations(str1, str2) 1. Create a temp string and store concatenation of str1 to str1 in temp. temp =
    2 min read
  • C++ Program for Check if given string can be formed by two other strings or their permutations
    Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pair from the array or their permutations. Examples: Input: str = "amazon", arr[] = {"loa", "azo", "ft", "amn", "lka"} Output: Yes The chosen strings are "amn" and "azo" whic
    4 min read
  • C++ Program to Check if it is possible to sort the array after rotating it
    Given an array of size N, the task is to determine whether its possible to sort the array or not by just one shuffle. In one shuffle, we can shift some contiguous elements from the end of the array and place it in the front of the array.For eg: A = {2, 3, 1, 2}, we can shift {1, 2} from the end of t
    3 min read
  • Check if a Binary String can be converted to another by reversing substrings consisting of even number of 1s
    Given two binary strings A and B of length N, the task is to check if the string A can be converted to B by reversing substrings of A which contains even number of 1s. Examples: Input: A = "10011", B = "11100"Output: YesExplanation: Reverse substring A[2, 5], 10011 → 11100.After completing the above
    9 min read
  • C++ Program to Check if all array elements can be converted to pronic numbers by rotating digits
    Given an array arr[] of size N, the task is to check if it is possible to convert all of the array elements to a pronic number by rotating the digits of array elements any number of times. Examples: Input: {321, 402, 246, 299} Output: True Explanation: arr[0] ? Right rotation once modifies arr[0] to
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences