Rotate Array
Pattern: Traversal and in-place tricks
Rotate right by k in place with three reversals - the whole array, then the first k, then the rest.
The problem
You are given an array nums and a number k of zero or more. Rotate the array to the right by k places, in place:
each element moves k positions to the right, and elements that fall off the end come back at the front. For example,
[1, 2, 3, 4, 5, 6, 7] rotated by 3 is [5, 6, 7, 1, 2, 3, 4].
The function name rotate matches LeetCode, where the function changes the array and returns nothing. Use the link above
for the exact statement.
Think first
- Where does the element at index
iend up after rotating byk? - What does rotating by
n(the length) do? Byn + 3? - Reverse
[1, 2, 3, 4, 5, 6, 7]. Compare it with the answer. What is wrong, and what would fix it?
Hints
Brute force, and why it fails
Rotating by one place k times, each time shifting every element, is O(n × k): up to 10¹⁰ steps at LeetCode's limits.
Copying into a new array at (i + k) % n is O(n) time but O(n) extra memory.
The key insight
Rotation swaps two blocks: the last k elements and the first n - k. Reversing everything swaps the blocks but flips
them, and reversing each block again flips them back. Three in-place reversals, O(1) extra memory.
Dry run
| k | 3 |
|---|
nums = [1, 2, 3, 4, 5, 6, 7] and k = 3. The answer should be [5, 6, 7, 1, 2, 3, 4], with the last 3 values moved to the front.
The plan
k = k mod n
reverse nums[0 .. n-1]
reverse nums[0 .. k-1]
reverse nums[k .. n-1]
function reverse(nums, left, right):
while left < right:
swap nums[left] and nums[right]
left = left + 1; right = right - 1
Complexity
- Time
O(n)- Space
O(1)
Each element is swapped at most twice across the three reversals. Only a few indexes are stored.
Edge cases
k = 0orka multiple ofn: afterk % nit is 0, and the two reversals cancel out.k > n:k % nhandles it, as in[1, 2]withk = 3, which is a rotation by 1.- One element: nothing changes.
I've built my logic, show the code
Java
class Solution {
public void rotate(int[] nums, int k) {
int n = nums.length;
k = k % n; // rotating n times changes nothing
reverse(nums, 0, n - 1); // whole array
reverse(nums, 0, k - 1); // the first k (they were the last k)
reverse(nums, k, n - 1); // the rest
}
private void reverse(int[] nums, int left, int right) {
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}C++
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = static_cast<int>(nums.size());
k = k % n; // rotating n times changes nothing
reverse(nums.begin(), nums.end()); // whole array
reverse(nums.begin(), nums.begin() + k); // the first k (they were the last k)
reverse(nums.begin() + k, nums.end()); // the rest
}
};Python
class Solution:
def rotate(self, nums: list[int], k: int) -> None:
n = len(nums)
k = k % n # rotating n times changes nothing
self.reverse(nums, 0, n - 1) # whole array
self.reverse(nums, 0, k - 1) # the first k (they were the last k)
self.reverse(nums, k, n - 1) # the rest
def reverse(self, nums, left, right):
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1Common mistakes
- Forgetting
k % n, which reverses past the end of the array whenk > n. - Rotating left instead of right, by reversing the first
n - kand then the lastk. - Assigning a new array to
numsinside the function, which does not change the caller's array in Java or Python.