Rotate String (LeetCode 796): Solution and Explanation

Easy
String
String Matching

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

  1. If len(s) != len(goal), return false, since a rotation never changes the length.
  2. Build doubled = s + s.
  3. Return whether goal is a substring of doubled. The match position, if any, is the number of shifts.

Step-by-step example

s = "abcde", goal = "cdeab"
  1. Both strings have length 5, so a rotation is possible.
  2. doubled = "abcdeabcde".
  3. Window at k = 0 is abcde; its first character a differs from goal's c.
  4. Window at k = 1 is bcdea; b differs from c.
  5. Window at k = 2 is cdeab, and all five characters match goal.
  6. 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 doubled
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

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).

Space

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.