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 - 10 <= 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, calculatek = k % nwherenis the length of the array. This ensureskis within the bounds of the array length and handles cases wherekis larger thann. - Reverse All: Reverse the entire array
numsfrom index0ton-1. - Reverse First
k: Reverse the firstkelements of the array (from index0tok-1). - Reverse Remaining
n-k: Reverse the remainingn-kelements of the array (from indexkton-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)
