Determine whether one string is a rotation of another (e.g. "abcde" and "cdeab").
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.
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)The "double it and search" idea appears in circular-buffer and cyclic-sequence checks — a neat constant-idea trick worth remembering.
A candidate tries every rotation offset in a nested loop (O(n^2)). What is the O(n) insight?