PPractick

DSA interview question

Rotate String

Easy · Algorithms · Topics: string

The problem

A marquee sign scrolls text by moving its first character to the end, over and over. Given the current text s and a target goal, can the sign ever show goal? Trying every rotation is O(n²). The elegant observation: every rotation of s appears as a substring of s + s. For example, "abcdeabcde" contains "cdeab". So the answer is "same length, and goal occurs in s + s", which is a single substring search.

Example: ("abcde", "cdeab") → true; ("abcde", "abced") → false.

Function signature

bool rotateString(const string& s, const string& goal);

Test cases

Input (s, goal)OutputExplanation
("abcde", "cdeab")trueRotate by 2
("abcde", "abced")falseNot a rotation
("aa", "a")falseDifferent lengths
("a", "a")trueRotation by 0
("abab", "baba")trueRotate by 1

(Confirm: a rotation moves characters from the front to the back; zero rotations count.)

How interviewers phrase it

Clarifying questions to ask

  1. Do the strings have to be the same length? (If not, false.)
  2. Does rotating by 0 count?
  3. Is the character set limited?

Follow-ups to expect

  1. "Why does s + s contain every rotation?"
  2. "Why check the lengths first?"
  3. "How fast is the substring search?"
  4. "What's the brute force?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in