Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. The rotation should happen in-place.

Constraints:

  • 1 <= nums.length <= 10^5
  • -2^31 <= nums[i] <= 2^31 - 1
  • 0 <= k <= 10^5

Example:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 step to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

Solution

Approach: Reversal Algorithm

This problem can be solved efficiently in O(n) time and O(1) extra space using the reversal algorithm.

  • Handle k reduction: First, reduce k to k % n, where n is the length of the array. If k is a multiple of n, no rotation is needed.
  • Reverse the entire array: Reverse all elements from index 0 to n-1.
  • Reverse the first k elements: Reverse the elements from index 0 to k-1.
  • Reverse the remaining n - k elements: Reverse the elements from index k to n-1.

This sequence of reversals effectively rotates the array to the right.

class Solution:
    def rotate(self, nums: list[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        n = len(nums)
        k %= n  # Reduce k to avoid unnecessary full rotations

        if k == 0:  # No rotation needed
            return

        # Helper function to reverse a sub-array
        def reverse_sub_array(arr, start, end):
            while start < end:
                arr[start], arr[end] = arr[end], arr[start]
                start += 1
                end -= 1

        # Step 1: Reverse the entire array
        reverse_sub_array(nums, 0, n - 1)

        # Step 2: Reverse the first k elements
        reverse_sub_array(nums, 0, k - 1)

        # Step 3: Reverse the remaining n - k elements
        reverse_sub_array(nums, k, n - 1)