Data Structures & AlgorithmsHardProduct Company SDE · array manipulation

Problem: Rotate the array [1, 2, 3, 4, 5, 6, 7] to the right by k = 3 using the three-reversal method. What is printed?

Problem: Rotate the array [1, 2, 3, 4, 5, 6, 7] to the right by k = 3 using the three-reversal method. What is printed?
a = [1, 2, 3, 4, 5, 6, 7]
k = 3 % len(a)
a.reverse()
a[:k] = reversed(a[:k])
a[k:] = reversed(a[k:])
print(a)
What is printed?
  1. A. [5, 6, 7, 4, 3, 2, 1]
  2. B. [5, 6, 7, 1, 2, 3, 4]
  3. C. [4, 5, 6, 7, 1, 2, 3]
  4. D. [7, 6, 5, 4, 3, 2, 1]

Correct answer: B. [5, 6, 7, 1, 2, 3, 4]

Reversing the whole array, then each part, gives the right rotation by k. Reversing only the first k elements is the trap that yields [5, 6, 7, 4, 3, 2, 1].

More Coding Interview Problems questions

Exams that ask this topic