How do you check whether one string is a rotation of another?

A string B is a rotation of A if B can be obtained by moving some characters from the start of A to its end, like "waterbottle" and "erbottlewat". The classic trick: B is a rotation of A exactly when both have the same length and B is contained in A + A.

Key Points: • A + A contains every possible rotation of A as a substring. • Check the lengths first, otherwise "abc" would wrongly be considered a rotation of "abcabc". • (A + A).contains(B) is short and easy to explain. Its cost depends on the search, typically O(n) to O(n²) in practice, and KMP guarantees O(n). • Empty strings: two empty strings are rotations of each other. • Variants: check rotation by exactly k places, or find the minimum rotation.

Code Example:

public class StringRotation {

    static boolean isRotation(String a, String b) {
        return a.length() == b.length() && (a + a).contains(b);
    }

    static String rotateLeft(String s, int k) {
        k = k % s.length();
        return s.substring(k) + s.substring(0, k);
    }

    public static void main(String[] args) {
        System.out.println(isRotation("waterbottle", "erbottlewat"));
        System.out.println(isRotation("spring", "gnirps"));
        System.out.println(isRotation("abc", "abcabc"));
        System.out.println("rotateLeft(\"interview\", 3) = " + rotateLeft("interview", 3));
        System.out.println(isRotation("interview", rotateLeft("interview", 3)));
    }
}

Output:

true false false rotateLeft("interview", 3) = erviewint true

Good to Know: "gnirps" is the reverse of "spring", not a rotation, which is why the second check prints false. Be careful with very short words, though: the reverse of "java" is "avaj", which happens to also be a rotation of "java". Interviewers sometimes use reversed strings to see whether you confuse the two ideas.

Interview Tip: A concise interview answer is:

"If the two strings have the same length and the second is a substring of the first concatenated with itself, it's a rotation, because A plus A contains every rotation of A. The length check is essential, and for a guaranteed linear-time search I'd mention KMP instead of contains."

Previous question: How do you reverse the order of words in a sentence in Java?

Next question: How do you find the longest common prefix of an array of strings?

More Java Strings interview questions

All Java Strings questions