The Wayback Machine - https://web.archive.org/web/20240907060356/https://www.geeksforgeeks.org/java-program-to-check-if-strings-are-rotations-of-each-other-or-not/
Open In App

Java Program to check if strings are rotations of each other or not

Last Updated : 13 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 = str1.str1
    2. 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.

 

 

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 method
    public static void main (String[] args)
    {
        String str1 = "AACD";
        String str2 = "ACDA";
  
        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 


Output: 

Strings are rotations of each other

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

Library Functions Used: 
strstr: 
strstr finds a sub-string within a string. 
Prototype: char * strstr(const char *s1, const char *s2); 
strcat: 
strncat concatenate two strings 
Prototype: char *strcat(char *dest, const char *src); 

Time Complexity: Time complexity of this problem depends on the implementation of strstr function. 
If implementation of strstr is done using KMP matcher then complexity of the above program is (-)(n1 + n2) where n1 and n2 are lengths of strings. KMP matcher takes (-)(n) time to find a substring in a string of length n where length of substring is assumed to be smaller than the string. 
Please refer complete article on A Program to check if strings are rotations of each other or not for more details!
 



Similar Reads

Java 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 (longest proper prefix which is also suffix) construct
2 min read
Javascript 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 (longest proper prefix which is also suffix) construct
2 min read
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 (longest proper prefix which is also suffix) constructi
6 min read
POTD Solutions | 14 Nov'23 | Check if strings are rotations of each other or not
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 String but will also help you build up problem-solving skills. We recommend you to try this problem on ou
3 min read
Check if given strings are rotations of each other or not
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 = CDABOutput: Strings are rotations of each other Input: S1 = ABCD, S2 = ACBDOutput: Strings are not rotations of each other Naive Approach: Follow the given steps to solve the problem Find all the positions of the first chara
15+ min read
Java Program to Check if two numbers are bit rotations of each other or not
Given two positive integers x and y, check if one integer is obtained by rotating bits of other. Input constraint: 0 < x, y < 2^32 Bit Rotation: A rotation (or circular shift) is an operation similar to shift except that the bits that fall off at one end are put back to the other end.More information on bit rotation can be found hereExample 1
3 min read
Javascript Program to Check if two numbers are bit rotations of each other or not
Given two positive integers x and y (0 < x, y < 2^32), check if one integer is obtained by rotating bits of the other. Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. Examples: Input : a = 8, b = 1Output : yesExplanation : Representati
3 min read
Java Program to Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1Output: Yes, All rows are rotated permutation of each other.Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2Output: No, Explanation : As 3, 2, 1 is not a rotated or circular permutation of 1, 2, 3
3 min read
Check if two numbers are bit rotations of each other or not
Given two positive integers x and y (0 < x, y < 2^32), check if one integer is obtained by rotating bits of the other. Bit Rotation: A rotation (or circular shift) is an operation similar to a shift except that the bits that fall off at one end are put back to the other end. Examples: Input : a = 8, b = 1Output : yesExplanation : Representati
6 min read
Javascript Program to Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1 Output: Yes All rows are rotated permutation of each other. Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2 Output: No Explanation : As 3, 2, 1 is not a rotated or circular permutation of 1, 2,
3 min read
Check if all rows of a matrix are circular rotations of each other
Given a matrix of n*n size, the task is to find whether all rows are circular rotations of each other or not. Examples: Input: mat[][] = 1, 2, 3 3, 1, 2 2, 3, 1 Output: Yes All rows are rotated permutation of each other. Input: mat[3][3] = 1, 2, 3 3, 2, 1 1, 3, 2 Output: No Explanation : As 3, 2, 1 is not a rotated or circular permutation of 1, 2,
8 min read
Java Program for Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
3 min read
Javascript Program To Check Whether Two Strings Are Anagram Of Each Other
Write a function to check whether two given strings are anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an anagram of each other. We strongly recommend that you click here and practice it, before moving on to t
7 min read
Check whether two Strings are Anagram of each other using HashMap in Java
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Hashmaps can be used to determine if two given strings are anagrams
3 min read
Javascript Program for Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
3 min read
Check if two strings can be made equal by swapping one character among each other
Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: Input: A = "SEEKSFORGEEKS", B = "GEEKSFORGEEKG" Output: Yes "SEEKSFORGEEKS" and "GEEKSFORGEEKG" After removing the elements which are the same and have the same index
10 min read
Check if two given strings are isomorphic to each other | Set 2 (Using STL)
Given two strings str1 and str2, the task is to check if the two strings are isomorphic to each other. Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in ‘str1’ map to the same character in ‘str2’. Examples: Input:
6 min read
Check whether two strings are anagrams of each other using unordered_map in C++
Write a function to check whether two given strings are an Anagram of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "abcd" and "dabc" are an Anagram of each other. Approach: Unordered Map can also be used to find if any two given strings are
3 min read
Check if two strings are permutation of each other
Write a function to check whether two given strings are Permutation of each other or not. A Permutation of a string is another string that contains same characters, only the order of characters can be different. For example, "abcd" and "dabc" are Permutation of each other. We strongly recommend that you click here and practice it, before moving on
14 min read
Check if two given Strings are Isomorphic to each other
Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in 'str1' map to the same character in 'str2'. Examples: Input: str1 = "aab", str2 = "xxy"Output: TrueExplanation: 'a' is mapped to 'x' and 'b' is mapped to 'y'. Inp
12 min read
Check whether two Strings are anagram of each other
Given two strings s1 and s2 consisting of lowercase characters, the task is to check whether the two given strings are anagrams of each other or not. An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, "act" and "tac" are anagrams of each other. Examples: Input: str
13 min read
Java Program to Find Minimum circular rotations to obtain a given numeric string by avoiding a set of given strings
Given a numeric string target of length N and a set of numeric strings blocked, each of length N, the task is to find the minimum number of circular rotations required to convert an initial string consisting of only 0's to target by avoiding any of the strings present in blocked at any step. If not possible, print -1.Note: A single rotation involve
4 min read
Check if bits in range L to R of two numbers are complement of each other or not
Given two non-negative numbers a and b and two values l and r. The problem is to check whether all bits at corresponding positions in the range l to r in both the given numbers are complement of each other or not. The bits are numbered from right to left, i.e., the least significant bit is considered to be at first position.Examples: Input: a = 10,
8 min read
Check if roots of a Quadratic Equation are reciprocal of each other or not
Given three numbers A, B, C which represents the coefficients(constants) of a quadratic equation [Tex]Ax^{2} + Bx + C = 0 [/Tex], the task is to check whether the roots of the equation represented by these constants are reciprocal of each other or not.Examples: Input: A = 2, B = -5, C = 2 Output: Yes Explanation: The given quadratic equation is [Te
8 min read
Java 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" which can be rearranged as "amazon". Input: str = "gee
4 min read
Check whether all the rotations of a given number is greater than or equal to the given number or not
Given an integer x, the task is to find if every k-cycle shift on the element produces a number greater than or equal to the same element. A k-cyclic shift of an integer x is a function that removes the last k digits of x and inserts them in its beginning. For example, the k-cyclic shifts of 123 are 312 for k=1 and 231 for k=2. Print Yes if the giv
12 min read
Minimize count of given operations required to make two given strings permutations of each other
Given two strings str1 and str2, the task is to count the minimum number of operations of the following three types on one of the two strings that are required to make str1 and str2 permutations of each other: Insert a character into the string.Remove a character from the string.Replace a character with another character from the string.Note: All t
13 min read
Python3 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" which can be rearranged as "amazon". Input: str = "gee
4 min read
Place K-knights such that they do not attack each other
Given integers M, N and K, the task is to place K knights on an M*N chessboard such that they don't attack each other. The knights are expected to be placed on different squares on the board. A knight can move two squares vertically and one square horizontally or two squares horizontally and one square vertically. The knights attack each other if o
15+ min read
Strings from an array which are not prefix of any other string
Given an array arr[] of strings, the task is to print the strings from the array which are not prefix of any other string from the same array.Examples: Input: arr[] = {"apple", "app", "there", "the", "like"} Output: apple like there Here "app" is a prefix of "apple" Hence, it is not printed and "the" is a prefix of "there"Input: arr[] = {"a", "aa",
13 min read
Article Tags :
Practice Tags :