SDE & MLE Prep

189. Rotate Array

Problem

Rotate the array nums to the right by k steps, in place: each element moves k positions right, wrapping around the end.

Example: nums = [1,2,3,4,5,6,7], k = 3 → [5,6,7,1,2,3,4]

Constraints: n ≤ 10⁵; k can be larger than n. Follow-up: O(1) extra space.

Rotating right by k = reverse all, then reverse the first k, then reverse the rest.

[1 2 3 4 5 6 7], k=3
reverse all     [7 6 5 4 3 2 1]
reverse [0,3)   [5 6 7 | 4 3 2 1]
reverse [3,7)   [5 6 7 | 1 2 3 4]

Complexity: O(n) time, O(1) space.

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        def rev(i, j):
            while i < j:
                nums[i], nums[j] = nums[j], nums[i]
                i, j = i + 1, j - 1
        n = len(nums)
        k %= n
        rev(0, n - 1); rev(0, k - 1); rev(k, n - 1)