String Rotation Check
Given two strings s and goal, return true if and only if goal is a rotation of s. A rotation is formed by moving some characters from the start of s to its end. For example, "cdeab" is a rotation of "abcde" because "abcde" shifted left by 2 gives "cdeab".
The classic solution checks if the strings have the same length and if goal is a substring of s + s. If goal is a rotation, it will appear as a contiguous substring in the doubled version of s.
Time complexity is O(n) for length check and O(n) for substring search. Space complexity is O(n) for the concatenated string.
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
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.
