00:00

Problem Statement

Input/Output Examples

Visual Explanation

A rotation splits a into two parts, x and y, and returns yx. Since a + a = xyxy, the string yx always sits in the middle of it.

Approaches

The first approach uses the concatenation trick. The second checks every possible rotation without building a new string.

Java Solutions

Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.

Complexity Analysis

Here n is the length of the strings. Building a + a needs O(n) memory; checking every shift uses constant memory but may compare up to n² characters.

Interview Tips and Recommended Approach

  • Never skip the length check. (a + a).contains(b) alone accepts any substring of a + a.
  • Explain why the trick works. Writing a = xy and the rotation as yx makes the proof one line.
  • Mention guaranteed linear time. Using KMP for the substring search makes the check O(n) in the worst case.
  • Test equal strings. A string is a rotation of itself (shift 0).

Recommended Approach: Concatenate and contains()

Why: it is short, clearly correct and fast in practice. It is the answer most interviewers expect, followed by a discussion of why it works.