Rotate Array · Optimal Solution

Three reversals compose a rotation.

A circular conveyor belt of packages needs its last k items moved to the front. Shifting one item at a time costs O(n·k) moves. The elegant alternative: reverse the entire belt, then reverse the first k items, then reverse the remaining n − k. Three in-place reversals achieve a full rotation. O(n) time. O(1) space.


Interactive

Watch the algorithm run


Concept

Three Reversals

Step 1: Reverse the entire array — this puts the tail block (which should move to front) into position, but both blocks are backwards.
Step 2: Reverse the first k elements — fixes the front block.
Step 3: Reverse the remaining n−k elements — fixes the back block.


Algorithm

Algorithm

Three reversals compose a rotation. Each reversal is an in-place two-pointer sweep — no extra array is needed.

  1. 1

    Normalize k

    Compute k = k % n. If k is zero or a multiple of n, the array is unchanged.

  2. 2

    Reverse the whole array

    Reverse all n elements. The last k elements are now at the front — but in the wrong order.

  3. 3

    Reverse the front block

    Reverse elements 0 through k − 1. They are now in the correct rotated order.

  4. 4

    Reverse the back block

    Reverse elements k through n − 1. The full rotation is complete.


Edge Cases

Edge Patterns

Understanding boundary behavior is as important as the main algorithm path.

k ≥ n

When k equals or exceeds n, the modulo operation reduces it. A full rotation of n steps returns the array to its original position.

k = 0

No rotation is needed. All three reversals cancel out — the array is untouched.


Complexity

Complexity

Time: O(n) — each element touched at most twice.
Space: O(1) — in-place swaps.