Check if Two Strings Are Rotations of Each Other in Java
Two strings are said to be rotations of each other if one string can be obtained by rotating the other string any number of times.
This is a popular interview problem that tests understanding of string logic and pattern matching.
Understanding String Rotation
If str2 is a rotation of str1, then it must:
- Have the same length as
str1 - Be a substring of
str1 + str1
Example 1
Input:
- String 1: ABCD
- String 2: CDAB
Output: Strings are rotations of each other
Example 2
Input:
- String 1: JAVA
- String 2: AVAJ
Output: Strings are rotations of each other
Example 3
Input:
- String 1: HELLO
- String 2: WORLD
Output: Strings are NOT rotations of each other
Logic Explanation
- Check if both strings have equal length.
- Concatenate the first string with itself.
- Check if the second string exists inside the concatenated string.
- If yes, the strings are rotations.
Java Program to Check String Rotation
import java.util.Scanner;
public class StringRotation {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();
if (str1.length() != str2.length()) {
System.out.println("Strings are NOT rotations of each other");
} else {
String combined = str1 + str1;
if (combined.contains(str2)) {
System.out.println("Strings are rotations of each other");
} else {
System.out.println("Strings are NOT rotations of each other");
}
}
}
}
Sample Output
Enter first string: ABCD
Enter second string: CDAB
Strings are rotations of each other
Important Notes
- Both strings must be of equal length.
- This approach runs in linear time.
- Case sensitivity matters.
Practice Challenges
- Check rotation without using
contains(). - Ignore case sensitivity while checking rotation.
- Find how many rotations are possible for a string.
This problem is a classic example of combining logic with string manipulation and is frequently asked in Java interviews.