Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: Is b a rotation of a? Check equal lengths and whether b occurs in a + a.

Problem: Is b a rotation of a? Check equal lengths and whether b occurs in a + a.
def is_rot(a, b):
    return len(a) == len(b) and b in a + a
print(is_rot("cabbage", "bagecab"), is_rot("abcd", "acbd"), is_rot("aa", "aaa"))
What is printed?
  1. A. True False False
  2. B. True False True
  3. C. True True False
  4. D. False False False

Correct answer: A. True False False

Every rotation of a is a substring of a + a ("cabbagecabbage" contains "bagecab"). "acbd" is a permutation but not a rotation. Without the length check, "aaa" would be found inside "aaaa". O(n) with a linear-time substring search.

More Coding Interview Problems questions

Exams that ask this topic