How do you check if one string is a rotation of another?
They must have the same length, and the second string must appear inside the first string written twice. For example, "waterbottle" doubled contains "erbottlewat".
Explain it simply
A rotation is like spinning a circular bangle: the letters keep their circular order but the starting point changes. If you write the string twice in a row, every possible starting point shows up somewhere inside that doubled string.
So "erbottlewat" is a rotation of "waterbottle" exactly when it appears inside "waterbottlewaterbottle", provided both have the same length.
Example
function isRotation(a, b) {
if (a.length !== b.length) return false;
return (a + a).includes(b);
}
console.log(isRotation("waterbottle", "erbottlewat")); // Output: true
console.log(isRotation("abc", "acb")); // Output: false
console.log(isRotation("abc", "abcd")); // Output: falseComplexity
Time O(n) with a linear substring search, space O(n).
What to say in the interview
"I first check that the lengths are equal, then test whether the second string is a substring of the first concatenated with itself. That is a single includes call, and with a good substring search it is O(n) time and O(n) space."
Common mistakes
- Skipping the length check, so a shorter string like "bc" would pass as a rotation of "abc" because it sits inside "abcabc".
- Trying every rotation manually, which is O(n squared).