Rotate String
Easyb is a rotation iff it is a substring of a+a
Problem
Return whether string a becomes b after some number of left rotations.
A rotation of s always appears inside s+s — just check if goal is a substring of that.
The idea
Concatenating a with itself contains every rotation of a as a contiguous substring. So the whole question collapses to a length check plus one substring search.
The trick
- Check the lengths match first, or 'a' would look like a rotation of 'aa'.
- (a + a).contains(b) — one line once you see it.
- O(n) with KMP, O(n²) with a naive search.
This one walks through the worked example rather than tracing the algorithm frame by frame — a full walkthrough is still to be drawn. The code and the idea below are the real solution.
Step 1 of 2. Here's the example — a='abcde', b='cdeab' Values: 0.
1return len(a)==len(b) and b in (a+a)Input
- array
- [0]
Output
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- s = "abcde", goal = "cdeab"
- Output:
- true
- Explanation:
- Rotating abcde gives cdeab.
Example 2
- Input:
- s = "abcde", goal = "abced"
- Output:
- false
- Explanation:
- Not a rotation → false.
Example 3
- Input:
- s = "a", goal = "a"
- Output:
- true
- Explanation:
- A single letter matches itself.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.