The problem. Given an array nums, rotate it to the right by k steps, where k is non-negative. One step moves the last element to the front. Do it in place with O(1) extra space.
Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
Input: nums = [-1, -100, 3, 99], k = 2
Output: [3, 99, -1, -100]Rotating right by k means the last `k` elements move to the front, in the same order, and everything else shifts right by k.
Rotating by the array's length n puts every element back where it started. So rotating by k is the same as rotating by k % n — with n = 7 and k = 10, only 3 steps actually matter. Always reduce k first.
Do exactly what the problem describes: take the last element, shift everything else right by one, put it at the front — and repeat that k times.
function rotate(nums, k) { const n = nums.length; k %= n; for (let step = 0; step < k; step++) { const last = nums[n - 1]; for (let i = n - 1; i > 0; i--) nums[i] = nums[i - 1]; // shift right by one nums[0] = last; }}Time O(n · k), space O(1). Each step shifts the whole array. With n = k = 100,000 that's ten billion moves.
We know exactly where each element ends up: index i moves to (i + k) % n — the % n wraps the last k elements around to the front. Write each one straight into its final slot in a new array, then copy it back.
function rotate(nums, k) { const n = nums.length; const result = new Array(n); for (let i = 0; i < n; i++) result[(i + k) % n] = nums[i]; // i moves k steps right for (let i = 0; i < n; i++) nums[i] = result[i];}Time O(n), space O(n). Every element moves once — but the second array breaks the "O(1) extra space" requirement.
Reversing an array in place is cheap and easy (two pointers swapping inward). And a rotation can be built from three reversals:
Why does it work? Reversing the whole array swaps the two blocks' positions — the last k elements land at the front — but it also flips each block internally. The next two reversals flip each block back, leaving the blocks swapped and correctly ordered.
Each phase highlights the segment being reversed. Try a k bigger than the array length and watch it shrink to k % n first.
C++'s std::reverse does exactly what our helper does, so the C++ version uses it directly.
Time O(n), space O(1). Every element is swapped at most twice across the three reversals.
O(n · k)k steps, and each one shifts all n elements.
O(1)Only one saved element per step.
k = 10 on 7 elements behaves like k = 3.Rotating left by k uses the same three reversals in a different order (reverse the first k, reverse the rest, then reverse everything). The "reverse, then reverse the parts" trick also reverses the words of a sentence in place.
O(n)Every element is moved once, to (i + k) % n.
O(n)A second array the size of the input.
O(n)The three reversals together swap each element at most twice.
O(1)Reversing swaps in place.