Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Rotate an array to the right by k steps in place, using O(1) extra space. Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3].

Problem: Rotate an array to the right by k steps in place, using O(1) extra space. Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3].
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([10, 20, 30, 40, 50, 60], 8))
What is printed?
  1. A. [30, 40, 50, 60, 10, 20]
  2. B. [60, 10, 20, 30, 40, 50]
  3. C. [20, 30, 40, 50, 60, 10]
  4. D. [50, 60, 10, 20, 30, 40]

Correct answer: D. [50, 60, 10, 20, 30, 40]

k = 8 mod 6 = 2. Reversing the whole array, then the first k and the remaining n − k elements, rotates right by 2: [50, 60, 10, 20, 30, 40]. Forgetting k %= n would index out of range; a left rotation by 2 gives [30, 40, 50, 60, 10, 20]. O(n) time, O(1) space.

More Coding Interview Problems questions

Exams that ask this topic