Rotate Array solution explained
To rotate an array k steps to the right in place, first reduce k modulo n, then reverse the whole array, reverse the first k elements, and reverse the remaining n - k. Three reversals put every element in its rotated position in O(n) time with O(1) extra space. An extra array or cyclic replacement also works; rotating one step at a time k times is the slow O(n × k) baseline.
By Evin JohnPublished 7 min read
What rotation means here
Given an array and a non-negative integer k, move each element k places to the right. Elements that fall off the end re-enter at the start. Equivalently, the last k elements move to the front, in their original order, and everything else shifts right. The array must be changed in place, and the follow-up asks for constant extra memory.
| Array | k | Result | Note |
|---|---|---|---|
| [10, 20, 30, 40, 50, 60] | 2 | [50, 60, 10, 20, 30, 40] | The last two move to the front |
| [10, 20, 30] | 4 | [30, 10, 20] | 4 mod 3 = 1 |
| [5] | 100 | [5] | A single element never moves |
| [1, 2, 3, 4] | 0 | [1, 2, 3, 4] | No rotation |
What the interviewer is after
Rotate Array looks trivial and has several correct answers with different costs, which makes it a good conversation starter. The interviewer wants to see whether you remember k mod n, whether you can reach a constant-space method, and whether you can justify it. The reversal trick is easy to code and easy to get subtly wrong; cyclic replacement is harder to code and shows a deeper grasp of how indices move.
Common follow-ups
- Rotate left instead of right. A left rotation by k equals a right rotation by n - k, or reverse the first k, then the rest, then the whole array.
- Rotate a string, or check if one string is a rotation of another. For the check, test whether the second string appears inside the first string written twice, with equal lengths.
- Rotate a linked list. Find the length, make the list circular, and cut it at the right place.
- Rotate a square matrix by 90 degrees. A different problem with a similar flavour: transpose, then reverse each row.
Slow and simple approaches
Rotating by one step means saving the last element, shifting everything right by one, and putting the saved value first. Doing that k times costs O(n × k), which is too slow when k is large, though reducing k mod n first caps it at O(n²). Copying into a new array is much better: element i goes to index (i + k) mod n, which takes O(n) time and O(n) space. In Python, slicing expresses the same thing in one line.
def rotate_with_copy(nums, k):
n = len(nums)
if n == 0:
return
k %= n
nums[:] = nums[n - k:] + nums[:n - k]Three reversals
Reverse the whole array: the last k elements are now at the front, but backwards, and the other n - k are at the back, also backwards. Reverse the first k to fix their order, then reverse the remaining n - k. With [10, 20, 30, 40, 50, 60] and k = 2, the full reversal gives [60, 50, 40, 30, 20, 10], fixing the front gives [50, 60, 40, 30, 20, 10], and fixing the back gives [50, 60, 10, 20, 30, 40].
def rotate(nums, k):
n = len(nums)
if n == 0:
return
k %= n
def flip(lo, hi):
while lo < hi:
nums[lo], nums[hi] = nums[hi], nums[lo]
lo += 1
hi -= 1
flip(0, n - 1) # whole array reversed: the last k now lead, but backwards
flip(0, k - 1) # put the first k back in order
flip(k, n - 1) # and the restEach element is swapped about twice in total, so the work is linear. Skipping k %= n breaks this code: with k larger than n, the second reversal would run past the end of the array.
Cyclic replacement in C++
Each element has a known destination, (i + k) mod n. Start at index 0, carry its value to its destination, pick up the value that was there, carry that one on, and so on until you return to the start. That loop is one cycle. The indices split into exactly gcd(n, k) cycles of equal length, so start one cycle at each of the indices 0 to gcd(n, k) - 1. Every element is moved exactly once.
#include <numeric>
#include <utility>
#include <vector>
// Cyclic replacement: follow each cycle of index -> (index + k) % n.
void rotateRight(std::vector<int>& nums, int k) {
int n = static_cast<int>(nums.size());
if (n == 0) return;
k %= n;
if (k == 0) return;
int cycles = std::gcd(n, k); // the moves split into gcd(n, k) separate cycles
for (int start = 0; start < cycles; ++start) {
int idx = start;
int carried = nums[start];
do {
int dest = (idx + k) % n;
std::swap(carried, nums[dest]); // drop the carried value, pick up the next
idx = dest;
} while (idx != start);
}
}std::gcd needs C++17. If you would rather not explain the gcd, count moves instead and stop when n elements have been placed, starting a new cycle each time you return to a start index. In production C++, std::rotate does this job; it takes the new first element as an argument, so a right rotation by k is std::rotate(begin, end - k, end).
Comparison
| Approach | Time | Extra space | Writes |
|---|---|---|---|
| One step, k times | O(n × k) | O(1) | About n per step |
| Copy to a new array | O(n) | O(n) | 2n with the copy back |
| Three reversals | O(n) | O(1) | About 2n |
| Cyclic replacement | O(n) | O(1) | Exactly n |
Edge cases
- k = 0, and k equal to n or a multiple of it: nothing should change.
- k much larger than n.
- An array of length 0 or 1, where k mod n needs a guard against division by zero.
- n and k sharing a factor, such as n = 6 and k = 2, which gives two cycles.
- Arrays with repeated values, which hide bugs because wrong moves can still look right. Test with distinct values.
Mistakes
- Forgetting k mod n.
- Rotating left when the problem asks for right, or mixing up which part to reverse first.
- Assuming one cycle covers everything in the cyclic method, which silently skips elements when gcd(n, k) is greater than 1.
- In Python, assigning nums = nums[-k:] + nums[:-k] instead of nums[:] = ..., which leaves the caller's list unchanged.
- Calling the slicing version O(1) space.
Explaining it
Fictional example
- Candidate
- First, k mod n, since rotating by n changes nothing.
- Candidate
- A copy would be linear time and space. For constant space I'll use three reversals. Reversing everything brings the last k elements to the front, just backwards. Then I reverse the first k and the last n minus k to restore their order.
- Candidate
- Each element gets swapped about twice, so it's linear time and constant space.
- Interviewer
- Can you move each element only once?
- Candidate
- Yes, by following cycles: each index goes to index plus k mod n. There are gcd of n and k cycles, so I start one from each of the first gcd indices.
Related problems
Reversing a suffix is also the last step of Next Permutation. Move Zeroes is another in-place array rearrangement, and 4Sum puts two pointers to work on a sorted array. Majority Element rounds out the constant-space set.
Using Natively in practice
Natively, on Mac or Windows, can read a rotation problem from a screenshot and set out the reversal and cycle approaches with code in its overlay. That helps when your output is off by one and you cannot see why. In a spoken mock round, its transcript shows whether you mentioned k mod n before coding. Read about Natively for coding interviews.
Questions people ask
How do you rotate an array in place?
Reduce k modulo n, reverse the whole array, reverse the first k elements, then reverse the remaining n - k. It takes O(n) time and O(1) extra space.
Why do you need k mod n when rotating an array?
Rotating by n returns the array to where it started, so only k mod n matters. Without it, k larger than n breaks index arithmetic and wastes work.
What is cyclic replacement in Rotate Array?
Each element moves directly to (i + k) mod n, carrying the displaced value onward until the cycle returns to its start. There are gcd(n, k) cycles, and every element moves once.
How do you rotate an array to the left?
A left rotation by k equals a right rotation by n - k. With reversals, reverse the first k, then the rest, then the whole array.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
