Rotate String

Check if string s can become goal after some rotations.

Example 1
Input: s="abcde", goal="cdeab" → Output: true
Example 2
Input: s="abcde", goal="abced" → Output: false

Solution Approach

If s+s contains goal, then goal is a rotation of s.

  • Check lengths match
  • Concatenate s+s
  • Check if goal is a substring of s+s
Java
public boolean rotateString(String s, String goal) {
    return s.length() == goal.length() && (s + s).contains(goal);
}
  • Time Complexity: O(n^2) with contains
  • Space Complexity: O(n)