mediumArrayMathArrays & Hashing

Rotate Array

mediumTime: O(n)Space: O(1)

Recognize the pattern

rotate array by k positionsin-placecyclic shift

Brute force idea

If you approach Rotate Array in the most literal way possible, you get this: Shift elements one by one, k times. It is a fair place to begin because it matches the surface of the question, yet it does not capture the deeper structure that makes the problem simpler.

Better approach

A calmer way to see Rotate Array is this: Reverse entire array, reverse first k, reverse rest. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Rotate Array is this: Three reverses achieve a rotation: reverse all, reverse [0.k-1], reverse [k.n-1]. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

A common way to get lost in Rotate Array is this: Not handling k > n — use k = k % n first. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Arrays & Hashing Pattern