Data Structures & AlgorithmsModerateAmazon · Microsoft OA

Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last characters removed.

Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last characters removed.
def rep(s):
    return s in (s + s)[1:-1]
print(rep("abab"), rep("aba"), rep("abcabcabc"), rep("a"))
What is printed?
  1. A. True False True True
  2. B. True True True False
  3. C. True False True False
  4. D. False False True False

Correct answer: C. True False True False

If s = uᵏ (k ≥ 2), rotating by |u| reproduces s, so s appears inside s + s away from both ends. 'aba' has no such rotation. A single character cannot be split into two or more copies; (s+s)[1:-1] = '' does not contain 'a'.

More Coding Interview Problems questions

Exams that ask this topic