Rotate String

Decide whether moving characters from the front of one string to its end can turn it into another string.

Given two strings s and goal, return true if s can turn into goal after some number of shifts, and false otherwise. A shift takes the first character of s off the front and puts it at the end, so "abcde" becomes "bcdea" after one shift.

Example 1
Input: s = "abcde", goal = "cdeab"
Output: true
Explanation: two shifts turn "abcde" into "bcdea" and then "cdeab".
Example 2
Input: s = "abcde", goal = "abced"
Output: false
Solution

The Idea

Picture the letters of "abcde" written around the rim of a wheel. Turning the wheel by one place sends a to the back, and you read "bcdea". Turn it again and you read "cdeab". After five turns the wheel shows "abcde" again. A string you can reach this way is called a rotation of s, so "abcde" has five rotations: "bcdea", "cdeab", "deabc", "eabcd" and "abcde" itself.

Example 1 asks whether "cdeab" is one of them, and it is, after two shifts. Example 2 asks about "abced". It has the same letters, but d and e have swapped places, and shifting never changes the order of the letters around the wheel. So the answer is false. Listing every rotation works for five letters, but is there a way to check them all at once?

Look at how "cdeab" is put together: the end of s, "cde", followed by the start of s, "ab". Every rotation has this shape, an end part of s followed by the start part that was moved behind it. Now write s twice in a row, as "abcdeabcde", and look at the picture below.

s + s is abcdeabcde. The goal cdeab sits inside it from index 2 to index 6: cde is the end of the first copy of s and ab is the start of the second copy.

In the row labelled s + s, the orange cells from index 2 to index 6 spell "cdeab", the same letters as the row labelled goal. The part marked "cde: end of the first copy" comes from the first copy of s, and "ab: start of the second copy" comes from the second. Wherever the cut falls, the end of the first copy runs straight into the start of the second.

So every rotation of s sits somewhere inside s + s, and the question "is goal a rotation of s?" turns into a search: does goal appear inside s + s?

Solution Approach

Turning that idea into code means looking at the plain way of trying every shift first, then settling two things: how to search the doubled string, and why the two lengths must be compared.

Trying every shift

What is the most direct way? Shift s one place at a time and compare the result with goal after each shift. In Java, s.substring(k) + s.substring(0, k) builds the rotation after k shifts. A string of n characters has n rotations, and comparing each one with goal can take up to n steps. That is about n² steps, and n new strings built along the way.

Searching the doubled string

How can the doubled string do the same job with less building? Build s + s once and call contains(goal) on it. String.contains returns true when goal appears somewhere inside the string as a run of characters next to each other, which is called a substring.

Can a match ever be something other than a rotation? Not when it has n characters. A run of n characters that starts at index k of s + s, for k from 0 to n, is exactly the rotation after k shifts. In the picture, k is 2. So a match of the right length is always a real rotation.

Comparing the lengths

Why does the length matter? s + s also holds shorter substrings, such as "bcd" inside "abcdeabcde", and those are not rotations, because a rotation keeps all n characters. For s = "aa" and goal = "a", the search alone finds "a" inside "aaaa", although "a" is not a rotation of "aa". Checking that both strings have the same length first rules these cases out.

Java Solution

The method rotateString fits in one line, which works in these steps:

  1. First, compare s.length() with goal.length(). If they differ, the && operator stops right there and the method returns false, without building anything.
  2. Otherwise, build the doubled string s + s, which holds every rotation of s.
  3. Return the result of (s + s).contains(goal).

The main method runs both examples, a goal equal to s, two empty strings, and s = "aa" with goal = "a". Its last line runs the search on "aa" and "a" again, this time without the length check.

Java
public class RotateString {

    public static boolean rotateString(String s, String goal) {
        // every rotation of s appears inside s + s
        return s.length() == goal.length() && (s + s).contains(goal);
    }

    public static void main(String[] args) {
        System.out.println(rotateString("abcde", "cdeab"));
        System.out.println(rotateString("abcde", "abced"));
        System.out.println(rotateString("abcde", "abcde"));
        System.out.println(rotateString("", ""));
        System.out.println(rotateString("aa", "a"));
        System.out.println(("aa" + "aa").contains("a"));   // without the length check
    }
}

Running it prints:

Output
true
false
true
true
false
true

Both examples come out as expected: true for "cdeab" and false for "abced". Look at the third line, true: "abcde" counts as a rotation of itself, after zero shifts. The fourth line is true as well, because two empty strings have the same length, 0, and the empty string is found inside any string, even inside "" + "".

The last two lines both use "aa" and "a". With the length check, the method prints false. Without it, ("aa" + "aa").contains("a") prints true, which would wrongly call "a" a rotation of "aa".

Complexity

The work is building s + s once and searching it for goal, where n is the length of s.

  • Time: O(n²) in the worst case, because String.contains may start a comparison at each of about n positions in s + s and compare up to n characters at each one. A smarter search such as KMP never steps back in s + s after a mismatch, which brings the search down to O(n).
  • Space: O(n), because the doubled string s + s has 2n characters and is built only once.