796. Rotate String
On LeetCode ->Problem¶
Given two strings s and goal, return whether goal is some left-rotation of s.
- Shift = move the first char of
sto the end. - Strings must have the same length.
Example:
Key trick¶
A string rotation must appear inside s + s.
- If
len(s) != len(goal), answer isFalse. - Otherwise,
goal in (s + s)is exactly the rotation check.
Trap¶
- Forgetting to check equal lengths first.
- Rebuilding every rotation one by one when a simpler check exists.
- Missing edge cases like identical strings, where zero shifts is allowed.
Why is it interesting?¶
It tests whether you can turn a simulation problem into a string property.
- Naive idea: try all rotations.
- Better idea: use the doubled-string observation.
Python solution¶
class Solution:
def rotateString(self, s: str, goal: str) -> bool:
# Rotations preserve length.
if len(s) != len(goal):
return False
# Every rotation of s appears as a substring of s + s.
return goal in (s + s)
Comment on my solution¶
Your solution is correct and interview-safe.
-
Good:
- Handles length mismatch.
- Easy to understand.
- Correctly allows zero shifts when
s == goal.
-
Can be improved:
- It is \(O(n^2)\) in the worst case because it builds up to
nrotated strings of lengthn. - The standard interview trick is shorter and cleaner:
- It is \(O(n^2)\) in the worst case because it builds up to
- One note:
- Under LeetCode constraints, your version is still fast enough.