Given an integer array nums, rotate the array to the right by k steps, where k is non-negative. You must do this in-place with O(1) extra space.

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 steps 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 approach leverages the idea that rotating an array can be achieved by a series of reversals. It's an in-place solution with O(1) extra space.

  • Handle k: First, calculate k = k % n where n is the length of the array. This ensures k is within the bounds of the array length and handles cases where k is larger than n.
  • Reverse All: Reverse the entire array nums from index 0 to n-1.
  • Reverse First k: Reverse the first k elements of the array (from index 0 to k-1).
  • Reverse Remaining n-k: Reverse the remaining n-k elements of the array (from index k to n-1).

This three-step reversal effectively rotates the array to the right.

Python Solution:

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  # Ensure k is within array bounds

        def reverse(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(nums, 0, n - 1)
        
        # Step 2: Reverse the first k elements
        reverse(nums, 0, k - 1)
        
        # Step 3: Reverse the remaining n - k elements
        reverse(nums, k, n - 1)