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 every shiftO(n²)
- Search inside s + sO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for strings of 100 letters | Verdict |
|---|---|---|---|
| Try every shift | O(n²) | Simple; quadratic | |
| Search inside s + s | O(n) | Best; one linear search |
n = length of s.
Edge cases to test
- Different lengths.
aaandagive false even thoughasits insideaaaa. Check the lengths first. - No shift needed.
sequal togoalis a rotation by 0, so true. - One letter.
aandagive true;aandbgive false. - Repeated letters.
aaabandabaagive true; KMP's fallback handles the repeats. - Same letters, wrong order.
lemonandmelonshare every letter but are not rotations: false.
Common mistakes
- Skipping the length check, so a shorter
goalfound insides + swrongly 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
- 1Clarify. Is zero shifts allowed? Can the lengths differ? Only lower-case letters?
- 2Give the brute force. Try all n cuts and compare each rotation with goal: O(n²).
- 3Spot the doubling. Every rotation is a window of s + s, so this is substring search.
- 4Code the search. Check the lengths, then search goal in s + s; use KMP for a linear guarantee.
- 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?