Rotate String – Solution & Complexity

Solution Walkthrough

1. Recognize the Pattern

  • Rotating a string does not change its length or multiset of characters.
  • More specifically, every rotation of s appears as a contiguous slice inside s + s.
  • So the problem reduces to checking equal lengths first, then substring containment.

2. Build the Algorithm

  • If s and goal have different lengths, return False immediately.
  • Otherwise form the doubled string s + s.
  • Return whether goal appears inside that doubled string.

3. Check Edge Cases

  • Identical strings should return True because zero rotations are allowed.
  • Single-character strings work naturally with the same check.
  • Repeated characters are safe because substring containment on s + s still distinguishes real rotations from lookalikes.

4. Solution and Complexity

  • The doubled-string trick captures every possible rotation exactly where it starts in s + s.
  • The algorithm runs in O(n) time for strings of length n and uses O(n) extra space for the doubled string.
def rotate_string(s: str, goal: str) -> bool:
    return len(s) == len(goal) and goal in (s + s)

FAQ