Static & Dynamic Arrays

Rotate Array

Medium
Solve it on LeetCode ↗

The problem

Rotate an array to the right by k steps, in place, with O(1) extra memory.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Normalize k = k % n (rotating by n is identity).
  2. 2Reverse the whole array.
  3. 3Reverse the first k elements.
  4. 4Reverse the remaining n − k elements.

Key insight

A rotation is two blocks swapping places; reversing the whole array puts each block in the right place but backwards — two more reversals fix their internal order.

The solution

Watch out for

  • Skipping k %= n crashes or wastes work when k ≥ n.
  • The cyclic-replacement solution also works but its group-counting logic is much easier to get wrong.