Rotate String (LeetCode 796): Solution and Explanation
A shift moves the first character of s to the end. Decide whether some number of shifts, including zero, turns s into goal.
Intuition
The brute force is to perform the shift n times and compare with goal after each one. That works, but every shift builds a new string, and it hides a much simpler picture.
Draw s around a circle. Shifting by k does not change the circle at all, it only changes where you start reading: start at index k, go around, and stop after n characters. So the question is whether goal can be read off the circle from some starting point.
To read around a circle with ordinary string tools, unroll it twice. In s + s, the n characters starting at index k are exactly s[k:] + s[:k], the rotation by k. Every rotation is a window of s + s, and every window of length n in s + s is a rotation.
That turns the problem into a substring search: same length, and goal occurs in s + s. The length check matters, because a shorter string like "a" also occurs in "aaaa" without being a rotation of "aa".
Approach: Substring search in s + s
- If
len(s) != len(goal), return false, since a rotation never changes the length. - Build
doubled = s + s. - Return whether
goalis a substring ofdoubled. The match position, if any, is the number of shifts.
Step-by-step example
s = "abcde", goal = "cdeab"
- Both strings have length 5, so a rotation is possible.
doubled = "abcdeabcde".- Window at k = 0 is
abcde; its first character a differs from goal's c. - Window at k = 1 is
bcdea; b differs from c. - Window at k = 2 is
cdeab, and all five characters match goal. - goal is found at index 2, so two shifts work and the answer is
true.
Code: Python, Java, C++
1class Solution:
2 def rotateString(self, s: str, goal: str) -> bool:
3 if len(s) != len(goal):
4 return False
5 doubled = s + s
6 return goal in doubled1class Solution {
2 public boolean rotateString(String s, String goal) {
3 if (s.length() != goal.length()) {
4 return false;
5 }
6 String doubled = s + s;
7 return doubled.contains(goal);
8 }
9}1class Solution {
2public:
3 bool rotateString(string s, string goal) {
4 if (s.size() != goal.size()) {
5 return false;
6 }
7 string doubled = s + s;
8 return doubled.find(goal) != string::npos;
9 }
10};Time and space complexity
O(n^2)
A plain substring search may compare up to n characters at each of n starting positions. With n at most 100 this is tiny. Using KMP or another linear matcher brings it to O(n).
O(n)
The doubled string holds 2n characters.
Other approaches
Try every shift (time O(n^2), space O(n))
For k from 0 to n - 1, build s[k:] + s[:k] and compare it with goal. It is the literal reading of the problem and easy to trust, but it allocates a new string per shift.
KMP on s + s (time O(n), space O(n))
Build the failure table of goal and run KMP over s + s. It guarantees linear time even for adversarial inputs like many repeated letters, at the cost of more code.
Compare modulo n without doubling (time O(n^2), space O(1))
For each start k, compare s[(k + j) % n] with goal[j]. It avoids building s + s and makes the circular reading explicit.
Common mistakes
- Skipping the length check.
goal = "a"is a substring of"aaaa"but not a rotation of"aa". - Thinking a rotation can reverse characters.
"dcba"is not a rotation of"abcd"; only the starting point moves. - Comparing sorted characters or counts. Equal letter counts are necessary but not sufficient, since order around the circle matters.
Frequently asked questions
Why does every rotation appear inside s + s?
The rotation by k is s[k:] + s[:k]. In s + s, starting at index k you read the tail s[k:] from the first copy and then the head s[:k] from the second copy, which is exactly that rotation.
Does zero shifts count?
Yes. If s already equals goal the answer is true, and goal is found at index 0 of s + s.
Is the built-in substring search fast enough?
Yes. With at most 100 characters even a quadratic search is instant. Mention KMP or Z-function if the interviewer asks for a guaranteed linear bound.
How many distinct rotations can a string have?
At most n. Strings made of a repeating block, like abab, have fewer distinct rotations, because shifting by the block length gives the same string back.