Code Logo

String Rotation Check

Published at25 Jul 2026
Medium 0 views
Like0

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

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
Recommendation Algorithm Flow for String Rotation Check

Solution Approach

function solution(s, goal) {
  return s.length === goal.length && (s + s).indexOf(goal) !== -1;
}

Best Answers

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