Interview Q&A / Data Structures & Algorithms

BeginnerQuick answerCoding1 min readUpdated 3 Oct 2026

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

SHORT ANSWER

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

js
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: false

Complexity

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).

#strings

Related questions

Practise more Data Structures & Algorithms questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Data Structures & Algorithms quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.