Rotate String - Problem

Given two strings s and goal, return true if and only if s can become goal after some number of shifts on s.

A shift on s consists of moving the leftmost character of s to the rightmost position. For example, if s = "abcde", then it will be "bcdea" after one shift.

Input & Output

Example 1 — Basic Rotation
$ Input: s = "abcde", goal = "cdeab"
Output: true
💡 Note: We can rotate "abcde" by moving "ab" from front to back: "abcde" → "cdeab"
Example 2 — No Valid Rotation
$ Input: s = "abcde", goal = "abced"
Output: false
💡 Note: No amount of rotation can transform "abcde" to "abced" because they have different character arrangements
Example 3 — Same String
$ Input: s = "aa", goal = "aa"
Output: true
💡 Note: The strings are identical, so goal is a rotation of s (0 rotations needed)

Constraints

  • 1 ≤ s.length, goal.length ≤ 100
  • s and goal consist of lowercase English letters

Visualization

Tap to expand
Rotate String Problem OverviewInput s:abcdeInput goal:cdeabRotation Process:abcdebcdeacdeabCheck: Is goal a rotation of s?Output: true
Understanding the Visualization
1
Input
Two strings s and goal
2
Process
Check if goal is a rotation of s
3
Output
Return true if rotation possible, false otherwise
Key Takeaway
🎯 Key Insight: If goal is a rotation of s, then goal must appear as substring in s+s
Asked in
Google 25 Amazon 18 Microsoft 12
32.0K Views
Medium Frequency
~15 min Avg. Time
850 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