Code Logo

String Rotation Check

Published at25 Jul 2026
Medium 1 views
Like0

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

Example 1
Input
"a","a"
Output
true
Explanation

Single char is rotation of itself

Example 2
Input
"ab","ab"
Output
true
Explanation

Same string

Example 3
Input
"",""
Output
true
Explanation

Empty strings are rotations

Example 4
Input
"abcde","cdeab"
Output
true
Explanation

cdeab is rotation of abcde

Example 5
Input
"abcde","abced"
Output
false
Explanation

Not a rotation

Algorithm Flow

Recommendation Algorithm Flow for String Rotation Check

Solution Approach

Check if s is a substring of goal concatenated with itself.

function rotateString(s, goal)
  if length(s) != length(goal) then return false
  if s == goal then return true
  return contains(goal + goal, s)

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

java
class Solution {
    public boolean solution(String s, String goal) {
        return s.length()==goal.length()&&(s+s).contains(goal);
    }
}