Rotate Array

Rotate an array right by k steps in place using three reverses.

Medium
Time O(n) Space O(1)
LeetCode
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#

Rotate Array
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());
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.