Skip to content
Preptima
mediumCodingEntryMidSenior

Rotate an array k positions to the right, in place.

Rotate array by k in place by normalising k modulo n, reversing the whole array, then reversing the first k and remaining n-k elements. It is O(n) time, O(1) extra space, and avoids the cyclic-replacement pitfalls unless write count matters. Use this ARRAYS answer to show the decision, trade-off, and evidence rather than a memorised definition.

4 min readUpdated 2026-08-15

Answer

Short answer

To rotate an array right by k in place, first reduce k with k = ((k % n) + n) % n, then reverse the entire array, reverse the first k elements, and reverse the remaining n-k elements. The three reversals turn A + B into B + A, so the array is rotated using O(n) time and O(1) extra space.

Was this answer helpful?

Likely follow-ups

  • Prove that the three reversals produce the same array as k single-step rotations.
  • The cyclic-replacement version needs gcd of n and k cycles. Why that number?
  • How would you rotate a linked list by k instead, and what changes in the cost?
  • If rotations arrive continuously and reads are rare, what would you store instead of rotating?

Related questions