 GeeksforGeeks App
Open App Browser
Continue

# Check for string rotation in Java

Given two strings s1 and s2, write a snippet to check whether s2 is a rotation of s1. Strings may contain duplicates. Examples:

```Input :  s1 = "ABCD", s2 = "CDAB"
Output : True
String s1 is rotation of s2.

Output : True

Input : s1 = ABCD, and s2 = ACBD
Output : False```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

One simple solution is to search first occurrence of s1 in s2. For every match, check if remaining string matches circularly. An efficient solution is to concatenate s1 with itself. s2 is a rotation of s1 if and only if it is a substring of the rotated string. In java we can either use string contains or indexOf to check for substring.

## 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).contains(str2));``    ``}` `    ``// Driver method``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String str1 = "AACD";``        ``String str2 = "ACDA";` `        ``if` `(areRotations(str1, str2))``            ``System.out.println("Yes");``        ``else``            ``System.out.printf("No");``    ``}``}`

Output:

`Yes`

The space complexity of the given Java program is O(n), where n is the length of the input strings str1 and str2, as we are only using additional space to store the input strings.

The time complexity of the program is O(n^2), where n is the length of the input strings str1 and str2. This is because the contains method is used to check if str2 is a substring of str1 concatenated with itself, which takes O(n^2) time in the worst case.

My Personal Notes arrow_drop_up
Related Tutorials