Given an integer array nums, rotate the array to the right by k steps. The rotation should be in-place if possible.

  • Constraints:
    • 1 <= nums.length <= 10^5
    • -10^9 <= nums[i] <= 10^9
    • 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

This problem can be solved in several ways, with varying space complexities. A common trick for in-place rotation involves reversals.

  • Understanding the effective rotations:
    • First, calculate k = k % n where n is the length of nums. This handles cases where k is larger than n.
  • Approach using Reversals (Optimal Space):
    • Step 1: Reverse the entire array. This brings the elements that should be at the end to the beginning (in reverse order) and vice-versa.
    • Step 2: Reverse the first k elements. This corrects the order of the elements that moved from the end to the front.
    • Step 3: Reverse the remaining n - k elements (from index k to n-1). This corrects the order of the elements that moved from the front to the end.
  • Example Walkthrough: nums = [1,2,3,4,5,6,7], k = 3 (n=7, k=3%7=3)
    1. Original: [1,2,3,4,5,6,7]
    2. Reverse all: [7,6,5,4,3,2,1]
    3. Reverse first k=3 elements: [5,6,7,4,3,2,1]
    4. Reverse remaining n-k=4 elements: [5,6,7,1,2,3,4] (Final Result)
  • Time Complexity: O(N) because each element is reversed at most three times.
  • Space Complexity: O(1) as the operations are performed in-place.
class Solution:
    def rotate(self, nums: list[int], k: int) -> None:
        n = len(nums)
        k %= n # Handle cases where k > n

        # Helper function to reverse a sub-array
        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)