← Back to libraryQuestion 62 of 273
⌨️Java CodingIntermediate

Check if Two Strings are Rotations of Each Other

📌 Definition:

Determine whether one string is a rotation of another (e.g. "abcde" and "cdeab").

📖 Detailed Explanation:

The elegant trick: b is a rotation of a if and only if they are the same length and b is a substring of a + a (a concatenated with itself). This covers every rotation offset in one check. O(n) with a good substring search.

💻 Solutions:
public static boolean isRotation(String a, String b) {
    return a.length() == b.length() && (a + a).contains(b);
}
function isRotation(a, b) {
  return a.length === b.length && (a + a).includes(b);
}
def is_rotation(a, b):
    return len(a) == len(b) and b in (a + a)
🔑 Key Points:
  • Lengths must be equal
  • b is a rotation of a iff (a + a).contains(b)
  • One concatenation covers all offsets
  • O(n) time, O(n) space
🌍 Real-World Example:

The "double it and search" idea appears in circular-buffer and cyclic-sequence checks — a neat constant-idea trick worth remembering.

🎯 Scenario-Based Interview Question:

A candidate tries every rotation offset in a nested loop (O(n^2)). What is the O(n) insight?