Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Rotate an array right by k in O(1) extra space with three reversals.

Problem: Rotate an array right by k in O(1) extra space with three reversals.
def rotate(a, k):
    n = len(a); k %= n
    def rev(i, j):
        while i < j: a[i], a[j] = a[j], a[i]; i += 1; j -= 1
    rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)
    return a
print(rotate([1, 2, 3, 4, 5, 6, 7], 10))
What is printed?
  1. A. [4, 5, 6, 7, 1, 2, 3]
  2. B. [5, 6, 7, 1, 2, 3, 4]
  3. C. [7, 1, 2, 3, 4, 5, 6]
  4. D. [3, 2, 1, 7, 6, 5, 4]

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

k = 10 mod 7 = 3. Reversing all gives 7..1, then reversing the first 3 (5, 6, 7) and the last 4 (1, 2, 3, 4) yields [5, 6, 7, 1, 2, 3, 4]. Rotating LEFT by 3 would give [4, 5, 6, 7, 1, 2, 3].

More Coding Interview Problems questions

Exams that ask this topic