Rotate Array
Medium · Two Pointers · Explanation and code example
One Liner
How it works
Many languages provide built-in ways to slice and concatenate arrays. We can simply take the last k elements and prepend them to the rest of the array. This leverages language features to express the rotation concisely, though under the hood it may use extra space.
Steps
- Compute the effective rotation
k % n. - Slice the array into two parts: the last
kelements and the firstn - kelements. - Concatenate them in reverse order and assign back to the original array.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)orO(n)depending on the language.
Things to watch for
Forgetting to Handle k Greater Than Array Length
When k is larger than the array length n, rotating by k is the same as rotating by k % n. Failing to normalize k with the modulo operation leads to unnecessary iterations or index out of bounds errors. Always compute k = k % n before proceeding.
Incorrect Reversal Boundaries in the Three-Reverse Approach
In the reverse approach, the three reversals must use precise boundaries: reverse the entire array, then reverse [0, k-1], then reverse [k, n-1]. Using wrong indices like reversing [0, k] instead of [0, k-1] shifts the boundary incorrectly and produces a wrong result.
Modifying Array While Iterating Without Proper Tracking
In the cyclic replacement approach, failing to track how many elements have been placed can cause infinite loops or incomplete rotations. This happens when n and k share a common divisor, creating multiple cycles. Always maintain a counter and start new cycles until all elements are moved.
Python code example
from typing import List
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
nums[:] = nums[-k % len(nums):] + nums[:-k % len(nums)]
C++ code example
class Solution {
public:
void rotate(vector<int>& nums, int k) {
std::rotate(nums.begin(), nums.end() - (k % nums.size()), nums.end());
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.