Home
DSA Patterns
Two Pointers
Rotate Array
Rotate Array
Rotate an array right by k steps in place with three reversals: the whole array, then the first k, then the rest.
Problem Understanding
Rotate Array: rotate nums to the right by k steps, in place. Each step moves the last element to the front.
Example: [1, 2, 3, 4, 5, 6, 7] with k = 3 becomes [5, 6, 7, 1, 2, 3, 4].
The Intuition: Reverse, Then Fix Each Block
Rotating right by k is the same as swapping two blocks: the last k elements and the first n − k, each staying in order.
- Reverse the whole array. The last
kare now at the front, and the rest at the back, but both blocks are backwards. - Reverse the first
k. That block is back in order. - Reverse the remaining
n − k. So is that one.
Each reversal is a pair of converging pointers that swap and step inward, so the whole thing is O(n) time and O(1) space. Take k = k mod n first, since a full rotation changes nothing.
Interactive Walkthrough
The shaded cells are the range being reversed, and lo and hi mark the pair just swapped. Watch the whole array flip first, then the two blocks flip back into order.
Dry Run Table
Input: [1, 2, 3, 4, 5, 6, 7], k = 3
| Step | Range | Array |
|---|---|---|
| start | — | 1, 2, 3, 4, 5, 6, 7 |
| reverse all | 0..6 | 7, 6, 5, 4, 3, 2, 1 |
| reverse first k | 0..2 | 5, 6, 7, 4, 3, 2, 1 |
| reverse the rest | 3..6 | 5, 6, 7, 1, 2, 3, 4 |
The Solution Template
Three in-place reversals. C++ uses std::reverse, which does the same swapping.
Rotate Array Code
1var rotate = function(nums, k) {2 const reverse = (lo, hi) => {3 while (lo < hi) {4 [nums[lo], nums[hi]] = [nums[hi], nums[lo]];5 lo++; hi--;6 }7 };8 const n = nums.length;9 k %= n;10 reverse(0, n - 1);11 reverse(0, k - 1);12 reverse(k, n - 1);13};
Edge Cases & Common Mistakes
- k > n: reduce with
k %= nfirst, or the ranges run off the end. - k = 0 or k = n: after the mod, nothing moves.
- One element: every reversal is empty.
- Rotating left instead of right: right rotation reverses all, then the first k; left rotation reverses the first k and the rest, then all.
Summary
Rotating right by k swaps two blocks: the last k and the first n − k. Reverse the whole array, then reverse each block back into order. Each reversal swaps from both ends inward. Take k mod n first. O(n) time, O(1) space.
More practice: DSA interview questions with answers · patterns cheat sheet
