Problem Statement

Rotate Array

You are given an array of numbers called nums and a number k. Your job is to shift every number to the right by k spots. Numbers that fall off the right end wrap back around to the front. You also have to change the original array directly, not build a brand new one. "In-place" means you fix up the array you were handed and do not make a separate copy.

mediumArrayMathArrays & HashingTime: O(n) · Space: O(1)

Signals to notice

rotate array by k positionsin-placecyclic shift

Brute force first

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.

The key insight

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.

Trace it on nums=[1,2,3,4,5,6,7], k=3

n=7, k = k % n = 3 % 7 = 3 (effective rotation)
reverse(0,6) reverse whole array -> [7,6,5,4,3,2,1]
reverse(0,k-1)=reverse(0,2) reverse first k -> [5,6,7,4,3,2,1]
reverse(k,n-1)=reverse(3,6) reverse rest -> [5,6,7,1,2,3,4]
no more reverses; array mutated in place
return [5,6,7,1,2,3,4]

What must stay true

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.

Shape of the loop

k = k mod n
reverse(nums, 0, n-1)      # whole array
reverse(nums, 0, k-1)      # first k
reverse(nums, k, n-1)      # the rest
# reverse(a,i,j): swap a[i],a[j]; i++, j-- while i<j

Pseudocode only — the full worked solution lives in the Solution tab.

Easy way to go wrong

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