796. Rotate String
On LeetCode ->Reformulated question¶
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 this question 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.
Solve the problem with idiomatic python¶
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)
Alternative with the same idea is unnecessary here because Python already gives the cleanest exact solution.
Pytest test¶
import pytest
@pytest.mark.parametrize(
("s", "goal", "expected"),
[
("abcde", "cdeab", True),
("abcde", "abced", False),
("aa", "aa", True),
("", "", True),
("a", "a", True),
("ab", "ba", True),
("ab", "ab", True),
("abc", "cab", True),
("abc", "acb", False),
("waterbottle", "erbottlewat", True),
("abc", "abcd", False),
],
)
def test_rotate_string(s, goal, expected):
assert Solution().rotateString(s, goal) is expected
Comment 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.