ProgrammingHardTCS NQT · Accenture

A string is a rotation of another when it can be obtained by moving some prefix to the end. The procedure below checks whether "waterbottle" is a rotation of "erbottlewat" by searching for "waterbottle" in the doubled string "erbottlewat" + "erbottlewat", counting every start position where the match occurs. What is printed?

A string is a rotation of another when it can be obtained by moving some prefix to the end. The procedure below checks whether "waterbottle" is a rotation of "erbottlewat" by searching for "waterbottle" in the doubled string "erbottlewat" + "erbottlewat", counting every start position where the match occurs. What is printed?
doubled = s2 + s2
count = number of positions i with doubled[i .. i+len-1] == s1
Print count
  1. A. 0
  2. B. 1
  3. C. 22
  4. D. 2

Correct answer: B. 1

The doubled string contains waterbottle at exactly one start position, so the count is 1. Searching in the undoubled string finds nothing, the doubled length is 22, and counting the substring wat in the doubled string gives 2.

More Pseudocode and Code Tracing questions

Exams that ask this topic