Rotate String

Easy Arrays & Hashing String Basics Original on LeetCode

Rotate String is a easy arrays & hashing problem solved with the string basics pattern. The best approach, optimal (search inside s + s), runs in O(n) time and O(n) space. Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (try every rotation) up.

Problem

You are given two strings s and goal. A shift takes the first character of s and moves it to the end, so "cloud" becomes "loudc".

Return true if s can be turned into goal after some number of shifts (possibly zero), otherwise false.

Examples

Example 1

Input
s = "cloud", goal = "oudcl"
Output
true
Why
Moving "c" and then "l" from the front to the back turns "cloud" into "oudcl".

Example 2

Input
s = "cloud", goal = "cluod"
Output
false
Why
Same letters, but no rotation of "cloud" produces this order.

Example 3

Input
s = "aa", goal = "a"
Output
false
Why
A rotation never changes the length.

Constraints

  • 1 <= s.length, goal.length <= 100
  • s and goal contain only lowercase English letters.

Solve it here

Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.

00:00
Testcase

Run checks the testcases above (3 examples, or your own). Submit also runs 14 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.

Solutions

Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.

ApproachTimeSpace
Brute force (try every rotation)O(n²)O(1)
Optimal (search inside s + s)O(n)O(n)

1Brute force (try every rotation)

TimeO(n²)n shifts, each compared in up to n steps.
SpaceO(1)Only indices; the rotation is never built.

For every shift k from 0 to n - 1, compare goal with the rotation of s that starts at index k, character by character with wrap-around.

  1. If the lengths differ, return false.
  2. For each k, check goal[i] == s[(k + i) % n] for all i.
  3. Return true on the first match, false if none matches.
class Solution {
    public boolean rotateString(String s, String goal) {
        int n = s.length();
        if (n != goal.length()) return false;
        for (int k = 0; k < n; k++) {
            boolean ok = true;
            for (int i = 0; i < n; i++) {
                if (s.charAt((k + i) % n) != goal.charAt(i)) { ok = false; break; }
            }
            if (ok) return true;
        }
        return false;
    }
}

2Optimal (search inside s + s)

TimeO(n)Building s + s is linear, and so is the substring search with KMP (built-in searches are fast in practice).
SpaceO(n)The doubled string has 2n characters.

Every rotation of s is a substring of s + s of length n: the rotation starting at k is (s + s)[k .. k + n - 1]. So goal is a rotation exactly when the lengths match and goal occurs in s + s. A linear-time matcher such as KMP makes the search O(n); the built-in substring search is fine for n <= 100.

  1. If the lengths differ, return false.
  2. Return whether s + s contains goal.
class Solution {
    public boolean rotateString(String s, String goal) {
        return s.length() == goal.length() && (s + s).contains(goal);
    }
}

Edge cases to test

  • Different lengths (always false)
  • s equal to goal (zero shifts, true)
  • Repeated letters like "abab" where several shifts match
  • Single-character strings

Hints

Hint 1

There are only n different rotations. You could try them all.

Hint 2

Write s twice in a row. Where do all rotations of s appear?

FAQ

What is the best time complexity for Rotate String?

Optimal (search inside s + s) runs in O(n) time and O(n) extra space. Building s + s is linear, and so is the substring search with KMP (built-in searches are fast in practice).

Which pattern does Rotate String use?

It is a arrays & hashing problem that uses the string basics pattern. Other problems with the same pattern: Longest Common Prefix, Minimum Changes To Make Alternating Binary String.

Is there a brute force solution for Rotate String?

Yes. Brute force (try every rotation) takes O(n²) time and O(1) space. For every shift k from 0 to n - 1, compare goal with the rotation of s that starts at index k, character by character with wrap-around.

Which edge cases should I test for Rotate String?

Different lengths (always false); s equal to goal (zero shifts, true); Repeated letters like "abab" where several shifts match; Single-character strings.