Skip to content
Related Articles
Open in App
Not now

Related Articles

Check if given strings are rotations of each other or not

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 24 Jan, 2023
Improve Article
Save Article

Given a string s1 and a string s2, write a function to check whether s2 is a rotation of s1. 

Examples: 

Input: S1 = ABCD, S2 = CDAB
Output: Strings are rotations of each other

Input: S1 = ABCD, S2 = ACBD
Output: Strings are not rotations of each other

Naive Approach: Follow the given steps to solve the problem

  • Find all the positions of the first character of the original string in the string to be checked.
  • For every position found, consider it to be the starting index of the string to be checked.
  • Beginning from the new starting index, compare both strings and check whether they are equal or not.
  • (Suppose the original string to is s1, string to be checked to be s2,n is the length of strings and j is the position of the first character of s1 in s2, then for i < (length of original string) , check if s1[i]==s2[(j+1)%n). Return false if any character mismatch is found, else return true.
  • Repeat 3rd step for all positions found.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
bool checkString(string& s1, string& s2, int indexFound,
                 int Size)
{
    for (int i = 0; i < Size; i++) {
        // check whether the character is equal or not
        if (s1[i] != s2[(indexFound + i) % Size])
            return false;
        // %Size keeps (indexFound+i) in bounds, since it
        // ensures it's value is always less than Size
    }
 
    return true;
}
 
int main()
{
 
    string s1 = "abcd";
    string s2 = "cdab";
 
    if (s1.length() != s2.length()) {
        cout << "s2 is not a rotation on s1" << endl;
    }
    else {
        // store occurrences of the first character of s1
        vector<int> indexes;
 
        int Size = s1.length();
 
        char firstChar = s1[0];
 
        for (int i = 0; i < Size; i++) {
            if (s2[i] == firstChar) {
                indexes.push_back(i);
            }
        }
 
        bool isRotation = false;
 
        // check if the strings are rotation of each other
        // for every occurrence of firstChar in s2
        for (int idx : indexes) {
            isRotation = checkString(s1, s2, idx, Size);
 
            if (isRotation)
                break;
        }
 
        if (isRotation)
            cout << "Strings are rotations of each other"
                 << endl;
        else
            cout
                << "Strings are not rotations of each other"
                << endl;
    }
    return 0;
}


Java




// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    // java program to check if two strings are rotation of
    // each other or not
    static boolean checkString(String s1, String s2,
                               int indexFound, int Size)
    {
        for (int i = 0; i < Size; i++) {
 
            // check whether the character is equal or not
            if (s1.charAt(i)
                != s2.charAt((indexFound + i) % Size))
                return false;
 
            // %Size keeps (indexFound+i) in bounds,
            // since it ensures it's value is always less
            // than Size
        }
 
        return true;
    }
 
    // Driver code
    public static void main(String args[])
    {
        String s1 = "abcd";
        String s2 = "cdab";
 
        if (s1.length() != s2.length()) {
            System.out.println(
                "s2 is not a rotation on s1");
        }
        else {
 
            ArrayList<Integer> indexes = new ArrayList<
                Integer>(); // store occurrences of the
                            // first character of s1
 
            int Size = s1.length();
 
            char firstChar = s1.charAt(0);
 
            for (int i = 0; i < Size; i++) {
                if (s2.charAt(i) == firstChar) {
                    indexes.add(i);
                }
            }
 
            boolean isRotation = false;
 
            // check if the strings are rotation of each
            // other for every occurrence of firstChar in s2
            for (int idx : indexes) {
                isRotation = checkString(s1, s2, idx, Size);
 
                if (isRotation)
                    break;
            }
 
            if (isRotation)
                System.out.println(
                    "Strings are rotations of each other");
            else
                System.out.println(
                    "Strings are not rotations of each other");
        }
    }
}
 
// This code is contributed by shinjanpatra


Python3




# Python3 program for the above approach
 
 
def checkString(s1, s2, indexFound, Size):
    for i in range(Size):
 
        # check whether the character is equal or not
        if(s1[i] != s2[(indexFound + i) % Size]):
            return False
 
        # %Size keeps (indexFound+i) in bounds,
        # since it ensures it's value is always less than Size
    return True
 
 
# driver code
s1 = "abcd"
s2 = "cdab"
 
if(len(s1) != len(s2)):
    print("s2 is not a rotation on s1")
 
else:
 
    indexes = []  # store occurrences of the first character of s1
    Size = len(s1)
    firstChar = s1[0]
    for i in range(Size):
        if(s2[i] == firstChar):
            indexes.append(i)
 
    isRotation = False
 
    # check if the strings are rotation of each other
    # for every occurrence of firstChar in s2
    for idx in indexes:
 
        isRotation = checkString(s1, s2, idx, Size)
 
        if(isRotation):
            break
 
    if(isRotation):
        print("Strings are rotations of each other")
    else:
        print("Strings are not rotations of each other")
 
# This code is contributed by shinjanpatra


C#




// C# program for the above approach
 
using System;
 
public class GFG {
 
    public static bool checkString(string s1, string s2,
                                   int indexFound, int Size)
    {
        for (int i = 0; i < Size; i++) {
 
            // check whether the character is equal or not
            if (s1[i] != s2[(indexFound + i) % Size])
                return false;
 
            // %Size keeps (indexFound+i) in bounds, since
            // it ensures it's value is always less than
            // Size
        }
 
        return true;
    }
 
    static public void Main()
    {
 
        string s1 = "abcd";
        string s2 = "cdab";
 
        if (s1.Length != s2.Length) {
            Console.WriteLine("s2 is not a rotation on s1");
        }
        else {
 
            // store occurrences of the first character of
            // s1
            int[] indexes = new int[1000];
            int j = 0;
 
            int Size = s1.Length;
 
            char firstChar = s1[0];
 
            for (int i = 0; i < Size; i++) {
                if (s2[i] == firstChar) {
                    indexes[j] = i;
                    j++;
                }
            }
 
            bool isRotation = false;
 
            // check if the strings are rotation of each
            // other for every occurrence of firstChar in s2
            for (int idx = 0; idx < indexes.Length; idx++) {
                isRotation = checkString(s1, s2, idx, Size);
 
                if (isRotation)
                    break;
            }
 
            if (isRotation)
                Console.WriteLine(
                    "Strings are rotations of each other");
            else
                Console.WriteLine(
                    "Strings are not rotations of each other");
        }
    }
}
 
// This code is contributed by akashish__


Javascript




<script>
 
 
function checkString(s1, s2, indexFound, Size)
{
    for(let i = 0; i < Size; i++)
    {
     
        //check whether the character is equal or not
        if(s1[i] != s2[(indexFound + i) % Size])return false;
         
        // %Size keeps (indexFound+i) in bounds, since it ensures it's value is always less than Size
    }
 
    return true;
}
 
// driver code
let s1 = "abcd";
let s2 = "cdab";
 
if(s1.length != s2.length)
{
    document.write("s2 is not a rotation on s1");
}
else
{
     
    let indexes = []; //store occurrences of the first character of s1
    let Size = s1.length;
    let firstChar = s1[0];
    for(let i = 0; i < Size; i++)
    {
        if(s2[i] == firstChar)
        {
            indexes.push(i);
        }
    }
 
    let isRotation = false;
 
    // check if the strings are rotation of each other for every occurrence of firstChar in s2
    for(let idx of indexes)
    {
        isRotation = checkString(s1, s2, idx, Size);
 
        if(isRotation)
            break;
    }
 
    if(isRotation)document.write("s2 is rotation of s1")
    else document.write("s2 is not a rotation of s1")
}
 
// This code is contributed by shinjanpatra
 
</script>


Output

Strings are rotations of each other

Time Complexity: O(n*n) in the worst case, where n is the length of the string.
Auxiliary Space: O(1)

Program to check if strings are rotations of each other or not using queue:

Follow the given steps to solve the problem

  • If the size of both strings is not equal, then it can never be possible.
  • Push the original string into a queue q1.
  • Push the string to be checked inside another queue q2.
  • Keep popping q2‘s and pushing it back into it till the number of such operations is less than the size of the string.
  • If q2 becomes equal to q1 at any point during these operations, it is possible. Else not.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
bool check_rotation(string s, string goal)
{
    if (s.size() != goal.size())
        return false;
 
    queue<char> q1;
    for (int i = 0; i < s.size(); i++) {
        q1.push(s[i]);
    }
 
    queue<char> q2;
    for (int i = 0; i < goal.size(); i++) {
        q2.push(goal[i]);
    }
 
    int k = goal.size();
    while (k--) {
        char ch = q2.front();
        q2.pop();
        q2.push(ch);
        if (q2 == q1)
            return true;
    }
    return false;
}
 
// Driver code
int main()
{
    string str1 = "AACD", str2 = "ACDA";
 
    if (check_rotation(str1, str2))
        printf("Strings are rotations of each other");
    else
        printf("Strings are not rotations of each other");
    return 0;
}


Java




// Java program for the above approach
 
import java.util.*;
 
class GFG {
    static boolean check_rotation(String s, String goal)
    {
        if (s.length() != goal.length())
            return false;
 
        Queue<Character> q1 = new LinkedList<>();
        for (int i = 0; i < s.length(); i++) {
            q1.add(s.charAt(i));
        }
 
        Queue<Character> q2 = new LinkedList<>();
        for (int i = 0; i < goal.length(); i++) {
            q2.add(goal.charAt(i));
        }
 
        int k = goal.length();
        while (k > 0) {
            k--;
            char ch = q2.peek();
            q2.remove();
            q2.add(ch);
            if (q2.equals(q1))
                return true;
        }
 
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "AACD";
        String str2 = "ACDA";
 
        // Function call
        if (check_rotation(str1, str2))
            System.out.println(
                "Strings are rotations of each other");
        else
            System.out.printf(
                "Strings are not rotations of each other");
    }
}
 
// This code is contributed by gauravrajput1


Python3




# Python3 program for the above approach
 
 
def check_rotation(s, goal):
 
    if (len(s) != len(goal)):
        skip
 
    q1 = []
    for i in range(len(s)):
        q1.insert(0, s[i])
 
    q2 = []
    for i in range(len(goal)):
        q2.insert(0, goal[i])
 
    k = len(goal)
    while (k > 0):
        ch = q2[0]
        q2.pop(0)
        q2.append(ch)
        if (q2 == q1):
            return True
 
        k -= 1
 
    return False
 
 
# Driver code
if __name__ == "__main__":
 
    string1 = "AACD"
    string2 = "ACDA"
 
    # Function call
    if check_rotation(string1, string2):
        print("Strings are rotations of each other")
    else:
        print("Strings are not rotations of each other")
 
        # This code is contributed by ukasp.


C#




// Include namespace system
using System;
using System.Threading;
using System.Collections.Generic;
 
public class GFG
{
  public static bool check_rotation(String s, String goal)
  {
    if (s.Length != goal.Length)
    {
      return false;
    }
    var q1 = new LinkedList<char>();
    for (int i = 0; i < s.Length; i++)
    {
      q1.AddLast(s[i]);
    }
    var q2 = new LinkedList<char>();
    for (int i = 0; i < goal.Length; i++)
    {
      q2.AddLast(goal[i]);
    }
    var k = goal.Length;
    while (k > 0)
    {
      k--;
      var ch = q2.First.Value;
      q2.RemoveFirst();
      q2.AddLast(ch);
      if (!q2.Equals(q1))
      {
        return true;
      }
    }
    return false;
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    var str1 = "AACD";
    var str2 = "ACDA";
 
    // Function call
    if (GFG.check_rotation(str1, str2))
    {
      Console.WriteLine("Strings are rotations of each other");
    }
    else
    {
      Console.Write("Strings are not rotations of each other");
    }
  }
}
 
// This code is contributed by aadityaburujwale.


Javascript




<script>
 
function check_rotation(s, goal){
 
    if (s.length != goal.length){
        return false;
    }
 
    let q1 = []
    for(let i=0;i<s.length;i++)
        q1.push(s[i])
 
    let q2 = []
    for(let i=0;i<goal.length;i++)
        q2.push(goal[i])
 
    let k = goal.length
    while (k--){
        let ch = q2[0]
        q2.shift()
        q2.push(ch)
        if (JSON.stringify(q2) == JSON.stringify(q1))
            return true
    }
 
    return false
}
 
 
// driver code
 
let s1 = "ABCD"
let s2 = "CDAB"
if (check_rotation(s1, s2))
    document.write(s2, " is a rotated form of ", s1,"</br>")
 
else
    document.write(s2, " is not a rotated form of ", s1,"</br>")
 
let s3 = "ACBD"
if (check_rotation(s1, s3))
    document.write(s3, " is a rotated form of ", s1,"</br>")
 
else
    document.write(s3, " is not a rotated form of ", s1,"</br>")
 
// This code is contributed by shinjanpatra.
 
</script>


Output

Strings are rotations of each other

Time Complexity: O(N1 * N2), where N1 and N2 are the lengths of the strings.
Auxiliary Space: O(N)

Efficient Approach: Follow the given steps to solve the problem

  • Create a temp string and store concatenation of str1 to str1 in temp, i.e temp = str1.str1
  • If str2 is a substring of temp then str1 and str2 are rotations of each other.

Example: 

str1 = “ABACD”, str2 = “CDABA”
temp = str1.str1 = “ABACDABACD”
Since str2 is a substring of temp, str1 and str2 are rotations of each other.

Below is the implementation of the above approach:

C++




// C++ program to check if two given strings
// are rotations of  each other
#include <bits/stdc++.h>
using namespace std;
 
/* Function checks if passed strings (str1
   and str2) are rotations of each other */
bool areRotations(string str1, string str2)
{
    /* Check if sizes of two strings are same */
    if (str1.length() != str2.length())
        return false;
 
    string temp = str1 + str1;
    return (temp.find(str2) != string::npos);
}
 
/* Driver code */
int main()
{
    string str1 = "AACD", str2 = "ACDA";
 
    // Function call
    if (areRotations(str1, str2))
        printf("Strings are rotations of each other");
    else
        printf("Strings are not rotations of each other");
    return 0;
}


C




// C program to check if two given strings are rotations of
// each other
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
/* Function checks if passed strings (str1 and str2)
   are rotations of each other */
int areRotations(char* str1, char* str2)
{
    int size1 = strlen(str1);
    int size2 = strlen(str2);
    char* temp;
    void* ptr;
 
    /* Check if sizes of two strings are same */
    if (size1 != size2)
        return 0;
 
    /* Create a temp string with value str1.str1 */
    temp = (char*)malloc(sizeof(char) * (size1 * 2 + 1));
    temp[0] = ' ';
    strcat(temp, str1);
    strcat(temp, str1);
 
    /* Now check if str2 is a substring of temp */
    ptr = strstr(temp, str2);
 
    free(temp); // Free dynamically allocated memory
 
    /* strstr returns NULL if the second string is NOT a
      substring of first string */
    if (ptr != NULL)
        return 1;
    else
        return 0;
}
 
/* Driver code */
int main()
{
    char* str1 = "AACD";
    char* str2 = "ACDA";
 
    // Function call
    if (areRotations(str1, str2))
        printf("Strings are rotations of each other");
    else
        printf("Strings are not rotations of each other");
 
    getchar();
    return 0;
}


Java




// Java program to check if two given strings are rotations
// of each other
 
class StringRotation {
    /* Function checks if passed strings (str1 and str2)
       are rotations of each other */
    static boolean areRotations(String str1, String str2)
    {
        // There lengths must be same and str2 must be
        // a substring of str1 concatenated with str1.
        return (str1.length() == str2.length())
            && ((str1 + str1).indexOf(str2) != -1);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "AACD";
        String str2 = "ACDA";
 
        // Fuinction call
        if (areRotations(str1, str2))
            System.out.println(
                "Strings are rotations of each other");
        else
            System.out.printf(
                "Strings are not rotations of each other");
    }
}
// This code is contributed by  munjal


Python3




# Python program to check if strings are rotations of
# each other or not
 
# Function checks if passed strings (str1 and str2)
# are rotations of each other
 
 
def areRotations(string1, string2):
    size1 = len(string1)
    size2 = len(string2)
    temp = ''
 
    # Check if sizes of two strings are same
    if size1 != size2:
        return 0
 
    # Create a temp string with value str1.str1
    temp = string1 + string1
 
    # Now check if str2 is a substring of temp
    # string.count returns the number of occurrences of
    # the second string in temp
    if (temp.count(string2) > 0):
        return 1
    else:
        return 0
 
 
# Driver code
if __name__ == "__main__":
    string1 = "AACD"
    string2 = "ACDA"
 
    # Function call
    if areRotations(string1, string2):
        print("Strings are rotations of each other")
    else:
        print("Strings are not rotations of each other")
 
# This code is contributed by Bhavya Jain


C#




// C# program to check if two given strings
// are rotations of each other
using System;
 
class GFG {
 
    /* Function checks if passed strings
    (str1 and str2) are rotations of
    each other */
    static bool areRotations(String str1, String str2)
    {
 
        // There lengths must be same and
        // str2 must be a substring of
        // str1 concatenated with str1.
        return (str1.Length == str2.Length)
            && ((str1 + str1).IndexOf(str2) != -1);
    }
 
    // Driver code
    public static void Main()
    {
        String str1 = "FGABCDE";
        String str2 = "ABCDEFG";
 
        // Function call
        if (areRotations(str1, str2))
            Console.Write("Strings are"
                          + " rotation s of each other");
        else
            Console.Write("Strings are "
                          + "not rotations of each other");
    }
}
 
// This code is contributed by nitin mittal.


PHP




<?php
// Php program to check if
// two given strings are
// rotations of each other
 
/* Function checks if passed
strings (str1 and str2) are
rotations of each other */
function areRotations($str1, $str2)
{
/* Check if sizes of two
   strings are same */
if (strlen($str1) != strlen($str2))
{
        return false;
}
 
$temp = $str1.$str1;
if(strpos($temp, $str2) != false)
{
        return true;
}
else
{
    return false;
}
}
 
// Driver code
$str1 = "AACD";
$str2 = "ACDA";
 
// Function call
if (areRotations($str1, $str2))
{
    echo "Strings are rotations ".
                  "of each other";
}
else
{
    echo "Strings are not " .
         "rotations of each other" ;
}
 
// This code is contributed
// by Shivi_Aggarwal.
?>


Javascript




<script>
// javascript program to check if two given strings are rotations of
// each other
 
    /* Function checks if passed strings (str1 and str2)
       are rotations of each other */
    function areRotations( str1,  str2)
    {
        // There lengths must be same and str2 must be
        // a substring of str1 concatenated with str1. 
        return (str1.length == str2.length) &&
               ((str1 + str1).indexOf(str2) != -1);
    }
     
    // Driver method
 
        var str1 = "AACD";
        var str2 = "ACDA";
 
        if (areRotations(str1, str2))
            document.write("Strings are rotations of each other");
        else
            document.write("Strings are not rotations of each other");
 
// This code is contributed by umadevi9616
</script>


Output

Strings are rotations of each other

Time Complexity: O(N), where N is the length of the string.
Auxiliary Space: O(N)

No extra space approach:

Instead of creating a new string as str1+str1, we use two pointers.

One pointer per string, also a count of the length of string that has been found the same since the last mismatch.

Every time there is a mismatch, we reset one of the pointer to 0 and start comparing again, once one pointer has run over any one string twice, we know we have checked for all possible rotations. Therefore we can return 0.

We keep track of a reset variable that helps us implement this, since i should only be incremented only when current character at i has been compared with current at j, when j is reset, the value of j changes to 0, now if we increment i without comparing s1[i]==s2[0] then we miss this comparison (we skip it). Therefore a reset variable keeps track of if there has been a reset given there was a mismatch, if yes then it increments i else i is only incremented when a match is found.

C++




// Code to check if two strings are rotation of one another
#include <bits/stdc++.h>
using namespace std;
 
int isCyclicRotation(string& p, string& q)
{
    int i = 0, j = 0, k = 0, n = p.length();
    bool reset = false;
    while (i < 2 * n) {
        if (k == n)
            return 1;
        if (p[i % n] == q[j % n]) {
            i++;
            j++;
            k++;
        }
        else if (reset) {
            reset = false;
            i++;
        }
        else {
            reset = true;
            j = 0;
            k = 0;
        }
    }
    return 0;
}
 
int main()
{
    string str1 = "AACD", str2 = "ACDA";
    if (isCyclicRotation(str1, str2)) {
        cout << "YES";
    }
    else {
        cout << "NO";
    }
    return 0;
}


Output

YES

Time Complexity: O(2*n) where n is the length of the string, this can be approximated to O(n)
Auxiliary Space: O(1) i.e. constant extra space.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!