sagelearnai

Rotate Array

Difficulty: Medium · Pattern: Two Pointers · LeetCode #189

Rotate nums to the right by k steps, in place. (k may exceed the length.) Return nothing.

Examples

text
nums = [1, 2, 3, 4, 5, 6, 7], k = 3  →  [5, 6, 7, 1, 2, 3, 4]
nums = [-1, -100, 3, 99], k = 2      →  [3, 99, -1, -100]

Hints

  1. Use k mod n.
  2. Reversing the whole array puts the last k elements at the front, but each part ends up backwards.

Approach

Triple reversal: with k %= n, reverse the whole array, then reverse the first k elements, then reverse the remaining n − k. Example: [1..7] with k = 3 becomes [7,6,5,4,3,2,1], then [5,6,7,4,3,2,1], then [5,6,7,1,2,3,4]. O(n) time, O(1) space.

Complexity

Time: O(n). Space: O(1).

Python solution
def rotate(nums, k):
    n = len(nums)
    k %= n
    def rev(i, j):
        while i < j:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1; j -= 1
    rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)
JavaScript solution
function rotate(nums, k) {
  const n = nums.length; k %= n;
  const rev = (i, j) => { while (i < j) { [nums[i], nums[j]] = [nums[j], nums[i]]; i++; j--; } };
  rev(0, n - 1); rev(0, k - 1); rev(k, n - 1);
}