Rotate String

Pattern: Strings basics and frequency

easy

Every rotation of s appears as a block inside s + s. So goal is a rotation exactly when it has the same length as s and appears in s + s.

The problem

Given two strings s and goal, return true if s can become goal after some number of shifts, where a shift moves the first character to the end. For example, "abcde" and "cdeab" give true, and "abcde" and "abced" give false.

The function name rotateString matches LeetCode. Use the link above for the exact statement and limits. The GFG link covers the same question.

Think first

  • List all rotations of "abc". Where do they all appear in "abcabc"?
  • Why must the lengths be checked separately?
  • How would you check one rotation at a time, and what does that cost?

Hints

    Brute force, and why it fails

    Build each of the n rotations and compare with goal: O(n²). One substring search in s + s is O(n) with KMP, and the built-in searches are fast in practice.

    The key insight

    Doubling the string lays every rotation side by side. A question about many rotations becomes one substring search.

    Dry run

    a0 
    b1 
    c2 
    d3 
    e4 

    s = abcde and goal = cdeab. Rotating moves letters from the front to the back.

    Step 1 of 3

    The plan

    if len(s) != len(goal): return false
    return goal appears in s + s
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    With KMP the search is linear (built-in searches are usually fast too). s + s takes 2n characters.

    Edge cases

    • Equal strings: true (zero shifts).
    • Different lengths, as in "aa" and "a": false, even though "a" appears in "aaaa".
    • Repeating strings like "abab": several shifts give the same string, which is fine.
    I've built my logic, show the code

    Java

    class Solution {
        public boolean rotateString(String s, String goal) {
            return s.length() == goal.length() && (s + s).contains(goal);   // every rotation is inside s + s
        }
    }

    C++

    class Solution {
    public:
        bool rotateString(string s, string goal) {
            return s.size() == goal.size() && (s + s).find(goal) != string::npos;   // every rotation is inside s + s
        }
    };

    Python

    class Solution:
        def rotateString(self, s: str, goal: str) -> bool:
            return len(s) == len(goal) and goal in s + s   # every rotation is inside s + s

    Common mistakes

    • Skipping the length check.
    • Comparing sorted letters, which accepts any anagram, not only rotations.
    • Building every rotation with new strings, which is O(n²).

    Similar problems