ProgrammingVery hardTCS NQT · Accenture

The procedure below counts the cyclic rotations of "abab" that are equal to "abab" itself, checking the rotations obtained by moving k characters from the front to the back for k = 0 to n - 1. What is printed?

The procedure below counts the cyclic rotations of "abab" that are equal to "abab" itself, checking the rotations obtained by moving k characters from the front to the back for k = 0 to n - 1. What is printed?
count = 0
for k = 0 to n - 1
    rotation = s[k..n-1] + s[0..k-1]
    if rotation == s then count = count + 1
end for
Print count
  1. A. 2
  2. B. 1
  3. C. 4
  4. D. 0

Correct answer: A. 2

The rotations are abab, baba, abab and baba for k = 0 to 3, so two of them equal the original. Leaving out the identity rotation gives 1, printing the length gives 4, and counting rotations equal to abba gives 0.

More Pseudocode and Code Tracing questions

Exams that ask this topic