Rotate String - Problem

Given two strings s and goal, determine if string s can be transformed into goal through a series of left rotations.

A left rotation operation moves the leftmost character of a string to the rightmost position. For example:

  • "abcde""bcdea" (after 1 rotation)
  • "abcde""cdeab" (after 2 rotations)
  • "abcde""deabc" (after 3 rotations)

Return true if s can become goal after some number of rotations, false otherwise.

Note: Both strings must have the same length for a valid transformation to be possible.

Input & Output

example_1.py — Basic Rotation
$ Input: s = "abcde", goal = "cdeab"
Output: true
💡 Note: After 2 left rotations: "abcde" → "bcdea" → "cdeab". The goal string is achievable.
example_2.py — No Valid Rotation
$ Input: s = "abcde", goal = "abced"
Output: false
💡 Note: No amount of rotations can transform "abcde" into "abced" because the character order is different (e and d are swapped).
example_3.py — Same String
$ Input: s = "abcde", goal = "abcde"
Output: true
💡 Note: The goal is the same as the original string (0 rotations needed).

Visualization

Tap to expand
abcdeCircular Viewabcdeabcdes + s = "abcdeabcde""cdeab" found!✓ Goal is a rotation of s
Understanding the Visualization
1
Original String
Start with string s arranged in a circle
2
Double the String
Create s + s to capture all rotations linearly
3
Search Pattern
Look for goal as a substring in the doubled string
4
Result
If found, goal is a valid rotation of s
Key Takeaway
🎯 Key Insight: Any rotation of a string appears as a substring in the string concatenated with itself (s + s)

Time & Space Complexity

Time Complexity
⏱️
O(n)

String concatenation O(n) + substring search O(n) using KMP or similar

n
2n
Linear Growth
Space Complexity
O(n)

Space for the concatenated string s + s

n
2n
Linearithmic Space

Constraints

  • 1 ≤ s.length, goal.length ≤ 100
  • s and goal consist of lowercase English letters
  • Both strings must have equal length for a valid transformation
Asked in
Google 25 Amazon 18 Microsoft 15 Meta 12
42.0K Views
Medium Frequency
~15 min Avg. Time
1.9K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen