Rotate Array
Rotate an array right by k steps in place using three reverses.
3 min read
two-pointers array
Problem#
Rotate nums to the right by k steps, in place, O(1) extra space.
Examples#
[1,2,3,4,5,6,7], k = 3→[5,6,7,1,2,3,4][-1,-100,3,99], k = 2→[3,99,-1,-100]
Constraints#
1 <= nums.length <= 10^5,0 <= k <= 10^5.
Hints#
Hint 1
Reverse the whole array, then reverse the first k and the rest separately.
Approach#
Extra array — O(n) space, simplest.
Three reverses — O(1) space.
reverse(0, n), reverse(0, k), reverse(k, n). Solution#
class Solution {public: void rotate(vector<int>& nums, int k) { const int n = nums.size(); k %= n; reverse(nums.begin(), nums.end()); reverse(nums.begin(), nums.begin() + k); reverse(nums.begin() + k, nums.end()); }};func rotate(nums []int, k int) { n := len(nums) k %= n rev := func(lo, hi int) { for lo < hi { nums[lo], nums[hi] = nums[hi], nums[lo] lo++ hi-- } } rev(0, n-1) rev(0, k-1) rev(k, n-1)}from typing import List
class Solution: def rotate(self, nums: List[int], k: int) -> None: n = len(nums) k %= n
def rev(lo: int, hi: int) -> None: while lo < hi: nums[lo], nums[hi] = nums[hi], nums[lo] lo += 1 hi -= 1
rev(0, n - 1) rev(0, k - 1) rev(k, n - 1)function rotate(nums, k) { const n = nums.length; k %= n; const rev = (lo, hi) => { while (lo < hi) { [nums[lo], nums[hi]] = [nums[hi], nums[lo]]; lo++; hi--; } }; rev(0, n - 1); rev(0, k - 1); rev(k, n - 1);}class Solution { private int[] nums;
public void rotate(int[] nums, int k) { this.nums = nums; int n = nums.length; k %= n; rev(0, n - 1); rev(0, k - 1); rev(k, n - 1); }
private void rev(int lo, int hi) { while (lo < hi) { int tmp = nums[lo]; nums[lo++] = nums[hi]; nums[hi--] = tmp; } }}function rotate(nums: number[], k: number): void { const n = nums.length; k %= n; const rev = (lo: number, hi: number): void => { while (lo < hi) { [nums[lo], nums[hi]] = [nums[hi], nums[lo]]; lo++; hi--; } }; rev(0, n - 1); rev(0, k - 1); rev(k, n - 1);}Editorial#
The identity rotate(A, k) = reverse(reverse(A[0..k-1]) ++ reverse(A[k..n-1])) is the classic trick. It works because reversing the whole array brings the last k elements to the front but in reversed order; reversing those two segments individually un-reverses them. Don’t forget k %= n — without it, k = n is a no-op that should still be O(1), not infinite-loop bait.
Complexity#
- Time: O(n).
- Space: O(1).
Concept revision#
Related#