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
sappears as a contiguous slice insides + s. - So the problem reduces to checking equal lengths first, then substring containment.
2. Build the Algorithm
- If
sandgoalhave different lengths, returnFalseimmediately. - Otherwise form the doubled string
s + s. - Return whether
goalappears inside that doubled string.
3. Check Edge Cases
- Identical strings should return
Truebecause zero rotations are allowed. - Single-character strings work naturally with the same check.
- Repeated characters are safe because substring containment on
s + sstill 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 lengthnand usesO(n)extra space for the doubled string.