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 INPUT String s: a b c d e String goal: c d e a b Shift Operation Example: "abcde" --> "bcdea" (move 'a' to end) s = "abcde" goal = "cdeab" ALGORITHM STEPS 1 Check Lengths len(s) == len(goal)? 5 == 5 [OK] 2 Concatenate s + s "abcde" + "abcde" "abcdeabcde" 3 Search for goal Is "cdeab" in (s+s)? abcdeabcde Found at index 2! 4 Return Result goal found --> true FINAL RESULT Rotation Path: Shift 0: abcde Shift 1: bcdea Shift 2: cdeab [OK] abcde rotates to Output: true s can become goal "cdeab" is a rotation of "abcde" Key Insight: If s can be rotated to become goal, then goal must be a substring of s+s. Concatenating s with itself (s+s) contains ALL possible rotations of s as substrings. Time Complexity: O(n) | Space Complexity: O(n) where n = length of string TutorialsPoint - Rotate String | Concatenation Check Approach
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