String Rotation Check
Given two strings s and goal, determine if s can become goal by rotating s by some number of positions. A rotation shifts characters from the beginning to the end. Return true if s is a rotation of goal, false otherwise.
For example, "abcde" rotated by 2 gives "cdeab" — so "abcde" and "cdeab" are rotations. "abcde" and "abced" are not rotations. An empty string is a rotation of itself. A single character is always a rotation of itself.
String rotation checking is a classic problem with an elegant trick: if s is a rotation of goal, then s must be a substring of goal + goal. This works because concatenating goal with itself contains every possible rotation.
The solution checks if the lengths are equal and if s is a substring of goal + goal. This runs in O(n) time using efficient substring search.
Edge cases include both strings empty (true), different lengths (false), same string (true, rotation by 0), and single characters (true if equal).
Example Input & Output
Single char is rotation of itself
Same string
Empty strings are rotations
cdeab is rotation of abcde
Not a rotation
Algorithm Flow
Solution Approach
Check if s is a substring of goal concatenated with itself.
First check that both strings have the same length — if not, rotation is impossible. If they are equal, they are trivially rotations. Otherwise, concatenate goal with itself and check if s appears as a substring. The concatenated string contains all possible rotations of goal.
Time complexity is O(n), space complexity is O(n) for the concatenated string.
Best Answers
class Solution {
public boolean solution(String s, String goal) {
return s.length()==goal.length()&&(s+s).contains(goal);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
