Skip to content
Problem 796 · LeetCode 796(opens in a new tab)

Rotate String

EasyStrings

A shift takes the first letter of a string and moves it to the end. One shift turns lemon into emonl, and a second turns it into monle.

Given the strings s and goal, decide whether some number of shifts (zero counts) turns s into goal. Answer true or false.

Example 1

Input:  s = "lemon", goal = "monle"
Output: true
Why:    two shifts move "le" to the end
2 more examples and the constraints

Example 2

Input:  s = "aab", goal = "aba"
Output: true
Why:    one shift moves the first "a" to the end

Example 3

Input:  s = "lemon", goal = "melon"
Output: false
Why:    same letters, but no shift puts them in this order

Constraints

  • 1 ≤ length of s, length of goal ≤ 100
  • Both strings hold only lower-case English letters

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try every shiftO(n²)
  2. Search inside s + sO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for strings of 100 lettersVerdict
Try every shiftO(n²)
Simple; quadratic
Search inside s + sO(n)
Best; one linear search

n = length of s.

Edge cases to test

  • Different lengths. aa and a give false even though a sits inside aaaa. Check the lengths first.
  • No shift needed. s equal to goal is a rotation by 0, so true.
  • One letter. a and a give true; a and b give false.
  • Repeated letters. aaab and abaa give true; KMP's fallback handles the repeats.
  • Same letters, wrong order. lemon and melon share every letter but are not rotations: false.

Common mistakes

  • Skipping the length check, so a shorter goal found inside s + s wrongly returns true.
  • Comparing only sorted letters, which accepts any reordering, not just rotations.
  • Building rotations with the wrong cut, such as s[k:] + s[:k + 1], which repeats a letter.

How to talk through it

  1. 1Clarify. Is zero shifts allowed? Can the lengths differ? Only lower-case letters?
  2. 2Give the brute force. Try all n cuts and compare each rotation with goal: O(n²).
  3. 3Spot the doubling. Every rotation is a window of s + s, so this is substring search.
  4. 4Code the search. Check the lengths, then search goal in s + s; use KMP for a linear guarantee.
  5. 5Test out loud. Run equal strings, different lengths and a repeated-letter case before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?